I've always had issues with prop('selected'), the following has always worked for me:
//first remove the current value
$("#selectBox").children().removeAttr("selected");
$("#selectBox").children().eq(index).attr('selected', 'selected');
$('#selectBox option').get(3).attr('selected', 'selected')
When using the above I kept getting errors in webkit (Chrome) saying:
"Uncaught TypeError: Object # has no method 'attr'"
This syntax stops those errors.
$($('#selectBox option').get(3)).attr('selected', 'selected');
Even simpler:
$('#selectBox option')[3].selected = true;
# Set element with index
$("#select option:eq(2)").attr("selected", "selected");
# Set element by text
$("#select").val("option Text").attr("selected", "selected");
when you want to select with top ways for set selection , you can use
$('#select option').removeAttr('selected');
for remove previous selects .
# Set element by value
$("#select").val("2");
# Get selected text
$("#select").children("option:selected").text(); # use attr() for get attributes
$("#select option:selected").text(); # use attr() for get attributes
# Get selected value
$("#select option:selected").val();
$("#select").children("option:selected").val();
$("#select option:selected").prevAll().size();
$("option:selected",this).val();
# Get selected index
$("#select option:selected").index();
$("#select option").index($("#select option:selected"));
# Select First Option
$("#select option:first");
# Select Last Item
$("#select option:last").remove();
# Replace item with new one
$("#select option:eq(1)").replaceWith("<option value='2'>new option</option>");
# Remove an item
$("#select option:eq(0)").remove();
I often use trigger ('change') to make it work
$('#selectBox option:eq(position_index)').prop('selected', true).trigger('change');
Example with id select = selectA1 and position_index = 0 (frist option in select):
$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');
you can set selectoption variable value dynamically as well as option will be selected.You can try following code
code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
$(function(){
$('#allcheck').click(function(){
// $('#select_option').val([1,2,5]);also can use multi selectbox
// $('#select_option').val(1);
var selectoption=3;
$("#selectBox>option[value="+selectoption+"]").attr('selected', 'selected');
});
});
HTML CODE:
<select id="selectBox">
<option value="0">Number 0</option>
<option value="1">Number 1</option>
<option value="2">Number 2</option>
<option value="3">Number 3</option>
<option value="4">Number 4</option>
<option value="5">Number 5</option>
<option value="6">Number 6</option>
<option value="7">Number 7</option>
</select> <br>
<strong>Select <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>