Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript onChange() on multiple elements

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)

like image 863
bhavicp Avatar asked Sep 25 '13 01:09

bhavicp


People also ask

Can I call multiple functions Onchange?

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.

Can you have two Onchange events?

You can only assign a handler to onChange once. When you use multiple assignments like that, the second one will overwrite the first one.

What can I use instead of Onchange?

onBlur should be used instead of onChange , unless absolutely necessary and it causes no negative consequences for keyboard only or screen reader users.

Can I use Onchange on Div?

No; the onchange attribute is only applicable to form field elements ( input , select , textarea , etc).


2 Answers

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

like image 66
PSL Avatar answered Oct 05 '22 20:10

PSL


What about:

var names = document.getElementsByName("attribute.Identifier Source");
for (var i = 0; i < names.length; i++) {
    names[i].onchange = function() {
        //do stuff
    }
}
like image 26
aet Avatar answered Oct 05 '22 18:10

aet