There is really strange behavior in jQuery >= 1.9! I'm not sure if it's a bug or not!
The basic HTML:
<select id="mySelect">
<option value="1" id="opt1">Option 1</option>
<option value="2" id="opt2">Option 2</option>
<option value="3" id="opt3">Option 3</option>
<option value="4" id="opt4">Option 4</option>
</select>
In jQuery <= 1.8.3, the below code works perfectly (Demo):
<script>
$(document).ready(function() {
$('#opt3').attr('selected', 'selected');// this line..
$('#mySelect').val($('#opt3').val()); // OR this line, OR both lines, alerts will always be the same:
alert($('#opt3').attr('selected')); // alert "selected"
alert($('#mySelect').val()); // alert "3"
});
</script>
While in jQuery >= 1.9.0, 1st alert is "selected", and 2nd alert is "1" not "3", and Option 1 selected not Option 3! (Demo)
If we comment out the line $('#opt3').attr('selected', 'selected');
, the dropdown correctly selects Option 3 but alert($('#opt3').attr('selected'));
alerts "undefined", Option 3 do not get the "selected" attribute! The code should look like this:
<script>
$(document).ready(function() {
//$('#opt3').attr('selected', 'selected');
$('#mySelect').val($('#opt3').val());
alert($('#opt3').attr('selected')); // alert "undefined", no "selected" attribute set !!
alert($('#mySelect').val()); // alert "3" correctly
});
</script>
If we comment out the line $('#mySelect').val($('#opt3').val());
, the alert($('#opt3').attr('selected'));
alerts "selected" correctly, but value of the select is not change, alerts "1"! The code should look like this:
<script>
$(document).ready(function() {
$('#opt3').attr('selected', 'selected');
//$('#mySelect').val($('#opt3').val());
alert($('#opt3').attr('selected')); // alert "selected" correctly
alert($('#mySelect').val()); // alert "1" !!
});
</script>
P.S.
btw, I know some people may suggest $('#opt3').prop('selected', true);
but that doesn't do any effect. What I'm trying to achieve, is to give Option 3 the "selected" attribute, and set the value of the select to "3". So is this a bug? Or am I doing something wrong?