Reputation: 81
I have multiple distinct select tags with the same options, and multi-select is enabled within each select tag.
<select name="city_id1" id="city_id1">
<option value="1">q</option>
<option value="2">s</option>
<option value="3">sasdad</option>
</select>
<select name="city_id2" id="city_id2">
<option value="1">q</option>
<option value="2">s</option>
<option value="3">sasdad</option>
</select>
I looked at https://api.jquery.com/change/ , and it showed me how to trigger an event when any option is selected, but in the example they gave
<script>
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$( "div" ).text( str );
})
.change();
</script>
it's aggregating the selected options in all the select tags together. I want the select options in city_id1 to be separate from city_id2. So for example, the city_id1 has its contents show up in its own div, and city_id2 has its contents show up in its own div.
Furthermore, there may be many select tags( not just 2), so it would be better for the solution to not hardcode city_id, and city_id2.
Upvotes: 0
Views: 43
Reputation: 359
When you use $("select")
, it will affect on each <select>
element's change event. If you want to make change on particular <select>
element's change event then use selector. As mentioned in previous answers also. So your code will look like,
$("#city_id1").change(function(){
// Your code
});
and same for the another one.
Upvotes: 0
Reputation: 37701
You need to modify the inner selector:
$( "select" )
.change(function () {
var str = "";
$( "option:selected", this ).each(function() { // <--- this line
str += $( this ).text() + " ";
});
$( "div" ).text( str );
})
.change();
That will ensure that you're selecting only the selected options which are the children of the changed select element.
$("option:selected", this)
behaves like:
$(this).find("option:selected")
Upvotes: 1