volodymyr3131 volodymyr3131 - 1 month ago 5
Javascript Question

Set default values for multiply elements javascript

I'm trying to set the default values for DOM elements using javascript.
First, I need to check if the field value is empty. If it is, then change the value into 0.
If it's not, then do nothing.

Text fields:

<input class="field" type="text" name="feature_value_1" value="" size="50" style="width: 350px;">
<input class="field" type="text" name="feature_value_2" value="1" size="50" style="width: 350px;">
<input class="field" type="text" name="feature_value_3" value="" size="50" style="width: 350px;">


The number of fields always changing.

I'm trying to do something like this

var feature_value = document.getElementsByName("feature_values_" + "/^\d+$/").value;
if(feature_value !== ""){
change the default values
}


And, as I understand, must use some loop, but I don`t know how to implement this. Can anyone help me?

Answer

There is no matching by a regular expression.

Best solution is to use a common className and loop over the collection.

var elems = document.getElementsByClassName("commonClass");

Other option is using querySelectorAll with a "starts with" match

var elems = document.querySelectorAll("[name^='feature_value_']");

and the loop

var i;
for (i=0; i<elems.length; i++) {
   if (!elems[i].value.length) {   //you might want to trim this 
       elems[i].value = "0";
   }
}

References:


Edit, add the runnable snippet:

var elems = document.querySelectorAll("[name^='feature_value_']");
var i;
for (i=0; i<elems.length; i++) {
   if (!elems[i].value.length) {   //you might want to trim this 
       elems[i].value = "0";
   }
}
<input class="field" type="text" name="feature_value_1" value="" size="50" style="width: 350px;">
<input class="field" type="text" name="feature_value_2" value="1" size="50" style="width: 350px;">
<input class="field" type="text" name="feature_value_3" value="" size="50" style="width: 350px;">