Nowhere can I find an example of checking the conditions of a select drop-down list via jQ / js. For example:

If the first item is selected in select, it displays the word "hello" . Can you please write the code on the example of this condition.

As select , the code is used:

 <select name="sex" id="sex"> <option value="b1"> Женский </option> <option value="b2" selected> Мужской </option> </select> 

    1 answer 1

    In order to get the selected value in jQuery there is a val method:

     $("#sex").val(); 

    Accordingly, the conditions for verification:

     /* Если выбран значение b1 (в данном случае первый пункт) */ if ($("#sex").val() === "b1") { alert("Woman"); /* В противном случае */ } else { alert("Not woman"); } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="sex" id="sex"> <option value="b1"> Женский </option> <option value="b2" selected> Мужской </option> </select> 


    Without jQuery (pure javascript) getting the selected item looks like this:

     var select = document.getElementById("sex"); var selectedValue = select.options[e.selectedIndex].value; 

    If you need to check it by the index number, you can check the compliance of e.selectedIndex === 1 .

    • Remove the snippet or make the code work - Yuri
    • @Yuri Code works, provided that the first item on the start page is selected. - Vadim Ovchinnikov
    • Well now it can be seen. It is necessary that the beginners see this - Yuri