0

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.

Set the default value in dropdownlist using jQuery

Online demo (Fiddle)

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
  • 1
    `prop()` in demo is working fine. What makes you say it doesn't work? – charlietfl Nov 18 '17 at 14:47
  • @charlietfl `prop()` doesn't add `selected="selected"` to `option 1` but `attr` does it. – Ali Soltani Nov 19 '17 at 05:18
  • Right....it's not supposed to. There is a difference between html attributes and dom node properties. Updating properties does not update the html attribute in the live source. Why does it matter if the attribute isn't changed? – charlietfl Nov 19 '17 at 05:57
  • @charlietfl I worked on form builder project like [this](https://formbuilder.online/) and I used jQuery plugin in that. I used `prop()` many times and it works properly but I need to change `selected` attribute in html to can check and set it in edit mode. I used `prop()` I thought I was wrong somewhere else. But finally I saw `prop()` didn't work. – Ali Soltani Nov 19 '17 at 06:57

0 Answers0