简体   繁体   中英

Attaching change listener to the jquery-chosen selects in a loop, not working

I am trying to init multiple chosen select in a loop:

var arr = ["#key1", "#key2"];

for (var p in arr) {
    $(arr[p]).chosen().change(function () {
        console.log($(arr[p]).chosen().val());
    });
}

where the elements are:

<div>
    <select multiple="" id="key1">
        <option value="A1">A1</option>
        <option value="B1">B1</option>
    </select>
</div>
<div>
    <select multiple="" id="key2">
        <option value="A2">A2</option>
        <option value="B2">B2</option>
    </select>
</div>

The problem is, the last 'change' event handler is getting attached to all select elements. For example, selecting an item from "key1" prints null since the .chosen().val() is getting the values from "key2". Any suggestions?

Actually I wanted to store the selected values of each chosen into different fields, for instance, into of this object:

var selected_values = {
    selected_keys1 : {},
    selected_keys2 : {}
}

You don't need a loop to do this. You can retrieve both elements by separating the id selector with a comma. In the change handler you can then reference the element that raised the event using the this keyword. Try this:

$("#key1, #key2").chosen().change(function () {
    console.log($(this).val());
});

Example fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM