简体   繁体   English

如何使用jQuery检查所选选项的整数值?

[英]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").value()返回TypeError。 $("#options").text() returns "" and $("#options").val() returns undefined . $("#options").text()返回""$("#options").val()返回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) 您可以执行以下两种方式之一(下面都进行了演示,请查看console.log)

you can listen to the .change() of the select element you have and then find the value of the selected option 您可以听取具有select元素的.change() ,然后找到selected选项的值

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. 如果您要在选定的div中获取文本,则需要在div上添加“ selected”伪选择器以指定您想要的选定选项。

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: 你可以看到更多的信息这里在jQuery的文档:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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