1

I have a number of field names that take the following format: 'Field1_ro', 'Field2_ro', 'Field3_ro'...

Is there a way I can set all fields that contain 'ro' to read only instead of using the following line everytime?

document.getElementById('Field1_ro').readOnly = true;
document.getElementById('Field2_ro').readOnly = true;
document.getElementById('Field3_ro').readOnly = true;
peterbonar
  • 559
  • 3
  • 6
  • 24
  • you can read this if you can use jQuery https://www.w3schools.com/jquery/jquery_ref_selectors.asp – Sirmyself Jan 30 '18 at 14:49
  • @Sirmyself: That's jQuery, and *contains* rather than suffix. (Not that there may not be a dupetarget for this, there may be.) – T.J. Crowder Jan 30 '18 at 14:52
  • @rlemon: That's *prefix*, not *suffix*. – T.J. Crowder Jan 30 '18 at 14:53
  • prefix, suffix or contains are different jquery selector operators that pretty much do the same since they work the same. Asker here did definetly not do the most basic researches so I gave him some hints in jQuery – Sirmyself Jan 30 '18 at 14:55

1 Answers1

1

You can use an attribute-ends-with selector on the id attribute, [id$=_ro] with querySelectorAll, and loop on the result:

document.querySelectorAll("[id$=_ro]").forEach(function(element) {
    element.readOnly = true;
});

That said, giving them a common class and using a class selector would be more typical. Or, ideally, adding the readonly attribute when they're defined instead of afterward. :-)


Note: The NodeList returned by querySelectorAll only got forEach relatively recently, but you can easily polyfill it on older browsers, see my answer here for an example of doing so.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875