I encountered to very simple but amazing issue with jQuery. I decide ask question to figure out reason of it.
I have a select
and two checkboxes like this:
Otion 1 is selected
<input type="checkbox" id="chk1">
Otion 2 is selected
<input type="checkbox" id="chk2">
<div>
<select id="select1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
And JS like below:
$('#chk1').change(function(){
if($(this).prop('checked'))
$('#select1 option:first').prop('selected',true);
else
$('#select1 option:first').prop('selected',false);
alert($('#select1 option:first').prop('selected'));
});
$('#chk2').change(function(){
if($(this).prop('checked'))
$('#select1 option:last').attr('selected',true);
else
$('#select1 option:last').attr('selected',false);
alert($('#select1 option:last').attr('selected'));
});
.prop
doesn't work but attr
works properly. Why???
In couple of posts like below people said that we can use .prop
for set selected
but in my code does not work.