Change All Value Of Inputs With Same Id In Javascript
Solution 1:
You need to change id="secure"
to class="secure"
first
HTML:
<inputtype="hidden"class="secure" name="secure" value="">
<inputtype="hidden"class="secure" name="secure" value="">
<inputtype="hidden"class="secure" name="secure" value="">
<inputtype="hidden"class="secure" name="secure" value="">
JavaScript:
<script>var els = document.getElementsByClassName("secure");
Array.prototype.forEach.call(els, function(el) {
// Do stuff here
el.setAttribute('123456');
});
</script>
Solution 2:
IDs should be unique - that's the point of them. Classes are for the opposite use, i.e. where there may be multiple instances of a single one.
Assumimg you change your IDs to classes, we can do the following:
[].forEach.call(document.querySelectorAll('.secure'), function(el) {
el.value = '123456';
});
Solution 3:
Don't use same id multi-pal times. Use class rather then id. To see result I remove type="hidden"
from your HTML.
var list = document.getElementsByClassName("secure");
for (var i = 0; i < list.length; i++) {
list[i].setAttribute("value", "12345");
}
<inputname="secure"value=""class="secure" /><inputname="secure"value=""class="secure" /><inputname="secure"value=""class="secure" /><inputname="secure"value=""class="secure" />
Solution 4:
This works - need to reference by class and then loop through all the elements to actually change the value.
<div><inputtype="text"class="secure"id="secure1"name="secure"value="123456"></div><div><inputtype="text"class="secure"id="secure2"name="secure"value="123456"></div><div><inputtype="text"class="secure"id="secure3"name="secure"value="123456"></div><div><inputtype="text"class="secure"id="secure4"name="secure"value="123456"></div><script>functionmyFunction() {
x=document.getElementsByClassName("secure");
for (i = 0; i < x.length; i++) {
x[i].value="100";
}
}
</script><buttononclick="myFunction()">
click me
</button>
Solution 5:
You need to add a class for each elements as in a document duplicate id's are not allowed.So we can better keep a common class of our element [also I changed your elements id's for keeping unique]. getElementsByClassName()
returns a nodeList of the DOM. We iterate over the element and put some value. Finally for testing I print value by id.
<inputtype="hidden"id="secure1"name="secure"value=""class="secure"><inputtype="hidden"id="secure2"name="secure"value=""class="secure"><inputtype="hidden"id="secure3"name="secure"value=""class="secure"><inputtype="hidden"id="secure4"name="secure"value=""class="secure"><script>var list = document.getElementsByClassName("secure");
for(var i = 0; i< list.length;i++){
document.getElementsByClassName("secure")[i].value='123456'
}
console.log(document.getElementById('secure2').value);
</script>
Post a Comment for "Change All Value Of Inputs With Same Id In Javascript"