Is it possible to assign the same onChange() to multiple elements (no jQuery)
At the moment i'm doing
var namefirst = document.getElementsByName("attribute.Identifier Source")[0];
namefirst.onchange = function () {//disable some stuff }
However, I have to do this onChange() for another 5 elements, and so i was wondering if it's possible to do this for all of them at once? Or am I going to have to do this for each element.
(I'm very new to Javascript)
Can I call multiple functions onChange? Create a function, call it on change event and inside that, call 2(or you can even call 20) functions.
You can only assign a handler to onChange once. When you use multiple assignments like that, the second one will overwrite the first one.
onBlur should be used instead of onChange , unless absolutely necessary and it causes no negative consequences for keyboard only or screen reader users.
No; the onchange attribute is only applicable to form field elements ( input , select , textarea , etc).
If you want to bind it at once, try using event delegation. i.e create a wrapper for the inputs and bind the change event to it, and detect the element based on event target and do your action.
Something like this:
HTML:
<div id="wrapper">
<input type="text" name="myText" />
<input type="text" name="myText" />
<input type="text" name="myText" />
<input type="text" name="myText" />
</div>
JS:
document.getElementById('wrapper').addEventListener('change', function(event){
var elem = event.target;
console.log(elem.name);
console.log(elem.tagName);
console.log(elem.type);
if(elem.name === "myText"){
console.log(elem.value);
}
});
So here the change event on input bubbles up to its parent and there you catch it and perform your operations.
Fiddle
What about:
var names = document.getElementsByName("attribute.Identifier Source");
for (var i = 0; i < names.length; i++) {
names[i].onchange = function() {
//do stuff
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With