I have the following HTML:
<select id="MySelector" multiple="multiple">
<option value="2">Option A</option>
<option value="7">Option B</option>
<option value="9">Option C</option>
<option value="12">Option D</option>
</select>
<div id="CheckSelected">click here to select</div>
I'm looking to loop through the options of the s开发者_运维知识库elect and determine which ones have been selected.
I'm looking to do something like this:
ArrayOfSelected = [];
$('#CheckSelected').click(function {
"if option is selected then add value to the array"
});
Thanks for your suggestions.
$('#MySelector').val()
gives you an array containing the values of the selected elements.
something like this should work for you. Find the option:selected
and for each one push the value into the array.
$('#CheckSelected').click(function() {
ArrayOfSelected.length = 0; //empty the array.
$("#MySelector option:selected").each(function() {
ArrayOfSelected.push($(this).val());
});
});
Code example on jsfiddle.
try this:
ArrayOfSelected = [];
$('#CheckSelected').click(function {
$('#MySelector option:selected').each(function(){
ArrayOfSelected.push($(this).val());
})
});
You can do this with live select option box clicks rather than having to select an option then click the "click here to select" div. Do the following:
var ArrayOfSelected = [];
$('select#MySelector').change(function(){
ArrayOfSelected.length = 0;
ArrayOfSelected.push($(this).val());
$("#picks").empty().append("<h1>selected: " + ArrayOfSelected + "</h1>");
});
The .change() function tells the callback function to execute when an option within the specified select input has been changed. So for every option box click, the callback will be executed...
Doing it this way will reduce the number of clicks the user has to do in order to add an option to the array.
update
I tested this in your jsfiddle link and it works the way you are wanting.
You can do it without looping with jQuery:
$('#CheckSelected').click(function() {
if($('#MySelector').val() == 'your_option') {
//add to array code
}
}
精彩评论