When initializing the list, I automatically set the required list item as selected, but sometimes the wrong one is selected. That's the salt ...

When I have on the list: 'orange' , 'banana', 'apple', 'strawberry)' Everything is ok. I ask:

$('.edit_selectCategory option:contains("' + "апельсин" +'")').prop('selected', true); 

And all the buzz getting 'orange'. But as soon as several similar words appear in the list, the last one is selected. Ie if there is still an orange orange in the list, then I will get an orange orange and not an orange .

 <select class="edit_selectCategory" style="width: 100%"></select> 

    1 answer 1

    Selector :containts searches for a substring, not “just that”.
    If you need an exact match and not otherwise, then something like this:

     $('.edit_selectCategory option:contains("Апельсин")') .filter((i, el) => el.innerHTML.toLowerCase().trim() === 'апельсин') .prop('selected', true); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class='edit_selectCategory'> <option>Банан</option> <option>Апельсин</option> <option>Яблоко</option> <option>Апельсин Лиловый</option> <option>Клубничка</option> </select> 

    First we search for everything with this string, then the .filter function is .filter , in which exact matches are already selected.

    Note:
    The selector :contains selects case-sensitive, i.e. the words Апельсин and апельсин will be different.

    • Thank. Works. - Bogdan Shulga
    • This construction does not work in IE ... "message": "Syntax error" => ... Yes, and the reducer swears at this code ( - Bogdan Shulga
    • Arrow functions are a fairly new phenomenon (although they have been around for a couple of years), so older IEs do not work, of course. You can rewrite the usual function. - user207618
    • IE11! In tune with the times so to speak) - Bogdan Shulga
    • one
      IE all have an amazing desire to put a stick in the wheel of progress. - user207618