user813813 user813813 - 2 months ago 7
Javascript Question

How do I attach an event to an array of select boxes?

I have an array of select boxes, with a class "taskcompleted". I want to be able to do something when a box is changed.

<select class = "taskcompleted" >
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>


I have used this javascript code

function initselects() {
var myselects = $('.taskcompleted');
myselects.each( function(){ // any select that changes.
console.log( $(this).val() );
}).change();
}


When the page loads, it is logging a change for each select box. I do not want this to happen. I want to only log a change after the page as has loaded.

Answer

You can use change() to attach the event to each select, like this:

function initselects() {
    $('.taskcompleted').change(function() {
        console.log($(this).val());
    });
}
Comments