Hello, how can you go around all the <option> in <select> 'e to find one that matches a certain text and recognize it .val() ?

    3 answers 3

    Option on jQuery:

     $('select').find('option').each(function() { if ( $(this).text() == 'Два' ) { document.write( $(this).val() ); } }) 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="One">Один</option> <option value="Two">Два</option> <option value="Three">Три</option> </select> 

      You need to select all option , for example using querySelectorAll

      Run through them in a loop, comparing the text of the element being checked with the desired one

      Get the value of the found item.

      For example:

       document.write( [].find.call(document.querySelectorAll('#select option'), function(el) { return el.text == 'Text3' }).value ); 
       <select id="select"> <option value="value1">Text1</option> <option value="value2">Text2</option> <option value="value3">Text3</option> <option value="value4">Text4</option> <option value="value5">Text5</option> <option value="value6">Text6</option> </select> 

        Take <select> , take all the <option> in it, take turns to compare their text content ( .textContent ) with the specified text and display the value ( .value ) of the desired:

         var text = "two"; var select = document.getElementById("select"); var options = select.options; for (var i = 0; i < options.length; i++) { if (options[i].textContent == text) { console.log(options[i].value); break; } } 
         <select id="select"> <option value="first">one</option> <option value="second">two</option> <option value="third">three</option> </select>