简体   繁体   中英

How to check the integer value of a selected option with jQuery?

Let's say I have a select options field like so:

  <select id="options">
    <option value=1>1</option>
    <option value=2>2</option>
  </select>

How can I check the value of the selected option?

$("#options").value() returns a TypeError. $("#options").text() returns "" and $("#options").val() returns undefined .

How can I check the selected integer value?

$( document ).ready(function() {
    var value = $('#options').val();
    //or
    var $('#options :selected').text();
});

Unless the script is executing too early your code should work.

您需要获取所选选项的值

$("#options option:selected").val()

you can do one of two ways (both demo'd below, check console.log)

you can listen to the .change() of the select element you have and then find the value of the selected option

or you can go through each option and find it's corresponding values

 $(document).ready(function() { $('#options').on('change', function() { console.log($(this).val()); }); $('#options option').each(function() { console.log('option value: '+ $(this).val()); }); }); 
 <select id="options"> <option value=1>1</option> <option value=2>2</option> </select> 

You will need to add the 'selected' pseudo selector on your div to specify that you want the selected option if you are looking to get the text within the selected div.

So to get the selected text would be:

$( "#options option:selected" ).text();

or if you want to get the value just use:

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

You can see more info here in the jquery docs:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM