peterbonar
peterbonar

Reputation: 599

JavaScript - Looping through elements and checking for length

I have some code that goes through the elements that end in '_ro' as below:

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

Is there a way I can check to see if there is an input, and if there is a value input, set it to read only?

Upvotes: 1

Views: 76

Answers (1)

Mamun
Mamun

Reputation: 68933

Try element.nodeName == 'INPUT' to check the node name and element.value.length to check the value length:

document.querySelectorAll("[id$=_ro]").forEach(function(element) {
  if(element.nodeName == 'INPUT' && element.value.length)
    element.readOnly = true;  
});
<input id="name_ro" type="text" value="Jhon"/>
<div id="div_ro">test</div>
<input id="phone_ro" type="text"/>

Upvotes: 2

Related Questions