jQuery - select option in select box [duplicate]
Possible Duplicate:
jQuery / Programmatically Selec开发者_JS百科t an Option in Select Box
I was wondering, is it possible to select an option from a selectbox/combobox directly from jQuery. For example I want to select the option with the value 5 in a select with values from 1 to 10.
The only solution I can think of is to remove all options and recreate them with the right selected value, but that's a bit unefficient.
Just treat the select box as you would any other input element:
$("#MySelectBox").val("5");
You can do this by adding the selected
attribute in <option>
tag.
$(document).ready(function () {
$('#btn2').click(function(){
$('#sel1 option[value=2]').attr('selected','selected');
});
$('#btn3').click(function(){
$('#sel1 option[value=3]').attr('selected','selected');
});
$('#btn5').click(function(){
$('#sel1 option[value=5]').attr('selected','selected');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<select id="sel1">
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
<option value='4'>Option 4</option>
<option value='5'>Option 5</option>
<option value='6'>Option 6</option>
<option value='7'>Option 7</option>
<option value='8'>Option 8</option>
<option value='9'>Option 9</option>
</select>
<input id="btn2" type=button value='Select 2' />
<input id="btn3" type=button value='Select 3' />
<input id="btn5" type=button value='Select 5' />
Of course you can
Just use this code to select option 5:
$("#ComboBox").val(5);
example
All you have to do is go around setting the attribute selected
to true
or selected
.
var arrayOfOptions = $('#mySelect option') //will return an array of options in the order they are found
Just iterate over them, something like:
for(var i=0; i<arrayOfOptions.length; i++) {
var opt = arrayOfOptions[i];
//feel free to check the index of i here if you want to set
//a particular index to selected or a range.
//similarly the range can be passed in as a function parameter.
$(opt).attr('selected','selected');
}
If I understand you correctly, you want to select the option with value=5 and mark it selected. If so, this should be it:
$("#selectBox[value='5']").attr('selected', 'selected');
This should also work:
$("#selectBox").attr('value', 5).attr('selected', 'selected');
精彩评论