There is such a select:

<select name="priority_quick_jump_box" id="priority_quick_jump_box" form="add_rule_form"> <option value="3">Низкий</option> <option value="4">Нормальный</option> <option value="5">Высокий</option> <option value="15">Не определен</option> </select> 

Also defined variable:

 var currPriority = "Высокий" 

There is some event in which the currPriority value (maybe not only "High") is set to select and makes this line selected. Here is the JS code:

 if (currPriority == "") { $("#priority_quick_jump_box [value='15']").attr("selected", "selected"); } else { $("#priority_quick_jump_box option").each(function () { if ($(this).text().indexOf(currPriority.slice(1)) >= 0) { $(this).attr('selected', 'selected'); } }); } 

I don’t understand what this is connected with, but sometimes it happens that when currPriority = "Высокий" the select value is not set, the first is set, "Low"! And sometimes it works. Can anyone have any idea what this is connected with? UPD: For example, now currPriority = "Высокий" enter image description here And after clicking on the line, "High" is not selected: enter image description here Although in some other lines everything is in order. And it happens only with the word "Vyskoy"

  • why here is a direct comparison: alert(currPriority === $(this).text()); , and here currPriority == $(this).text().slice(1) without the first character? and for some reason the boolean value is compared with the number - Grundy
  • And what version of jQuery? In new versions, you must use prop instead of attr to install select - Crantisz
  • @Grundy, code corrected - S.Ivanov
  • @Crantisz, jquery-1.7.1.min - S.Ivanov

2 answers 2

Use the contains selector:

 var currPriority = "Высокий"; $('#setValue').on('click', function(e){ // Если не очистить это свойство, то сработает только раз // Иначе после выбора пользователем другого значения, установка ничего не даст $('#priority_quick_jump_box option:selected').removeProp('selected'); $(`#priority_quick_jump_box option:contains('${currPriority}')`).prop('selected', 'true'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="priority_quick_jump_box" id="priority_quick_jump_box" form="add_rule_form"> <option value="3">Низкий</option> <option value="4">Нормальный</option> <option value="5">Высокий</option> <option value="15">Не определен</option> </select><br /> <input type='button' id='setValue' value='Установить "Высокий"' /> 

    The problem was simpler than it seemed. Adding currPriority.trim() all earned