I have multiple select menus where the pattern is :
<s开发者_JAVA百科elect name='device$num' id='device$num' size='8' multiple='multiple' >"
I want to display the values out when any one of these select changes.
I tried this but sometimes I get undefined values from the alert. what is wrong?
<script>
\$("select[id^=device]").change(function () {
\$("#paramselection").html(" ");
\$("#voltageselection").html(" ");
// IF THE DATA HAS CHANGED, FIND OUT WHICH DATA SECTIONS ARE STILL VALID
\$("select[id^=device] :selected").val(function(index, value) {
alert(value);
});
});
</script>
Another question, how do i pattern match such that id^=device\d+? Sorry, I am more familar with perl
In order to avoid redundant DOM selection, cache the device
elements, and use that to get the selected values of all of them
From the devices
set, use find()
(docs) with the selected-selector
(docs) to get the selected <option>
elements.
Then use map()
(docs) to create a jQuery object containing the values, then get()
(docs) to retrieve the Array from the object.
// cache all the "device" elements as you assign the "change" handler
var devices = $("select[id^=device]").change(function () {
$("#paramselection").html(" ");
$("#voltageselection").html(" ");
// from the "devices" variable, find selected options, and
// create an Array of the values
var selected = devices.find('option:selected')
.map(function(){
return this.value;
}).get();
alert( selected ); // will alert an array of the selected values
});
Change your alert to this to get the selected text:
\$("select[id^='device'] option:selected").each(function() {
alert($(this).text());
});
精彩评论