Why does the software selection of an option in select work only once? Code:

$(document).ready(function() { $("#default").attr('selected', 'selected'); }); $("button").click(function(){ $("select option:contains('two')").attr('selected', 'selected'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <select> <option>----------</option> <option id="default">one</option> <option>two</option> <option>three</option> </select> <button>set two</button> 

Now I guess ... What could be the reason?

  • for a select, you can use val(...) to set, get the value - Grundy
  • @Grundy thanks for the hint, I would have suffered for a long time. did everything according to the answer of an experienced member ru.stackoverflow.com/questions/245920/… - perfect
  • That question / answer is too old, several versions of jquery have changed already, the differences in them are quite significant - Grundy
  • @Grundy, as it turned out, the val method does not always work, you change it to the prop method and it copes. apparently they are not the same. With this string "02.20.11.114 Cedar logs for sawing and planing" and the connected select2 plugin, the val method failed. - perfect
  • select2 plugin has its own methods for setting the value - Grundy

2 answers 2

Since version 1.6 .attr() works directly with the attribute of the element and in some cases the result is not quite expected, it is desirable to use .prop ...

 $(document).ready(function() { $("#default").prop('selected', true); }); $("button").click(function(){ $("select option:contains('two')").prop('selected', true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <select> <option>----------</option> <option id="default">one</option> <option>two</option> <option>three</option> </select> <button>click</button> 

  • @perfect from version 1.6 .attr () works directly with the element attribute and in some cases the result is not quite expected, it is advisable to use .prop ... - C.Raf.T

To assign properties like checked , delected , disabled you must use prop , not attr . In any case, to select a value in select it is better to use val :

 $(function() { $("#default").prop('selected', true); }); $("button").click(function(){ $("select").val('two'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <select> <option>----------</option> <option id="default">one</option> <option>two</option> <option>three</option> </select> <button>set two</button>