jQuery 如何检查一个选项是否被选中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10213620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:57:10  来源:igfitidea点击:

How to check if an option is selected?

jqueryselectoption

提问by 0x56794E

$('#mySelectBox option').each(function() {
    if ($(this).isChecked())
       alert('this option is selected');
     else
       alert('this is not');
});

Apparently, the isCheckeddoesn't work. SO my question is what is the proper way to do this? Thanks.

显然,这isChecked不起作用。所以我的问题是这样做的正确方法是什么?谢谢。

回答by iambriansreed

UPDATE

更新

A more direct jQuery method to the option selected would be:

对所选选项更直接的 jQuery 方法是:

var selected_option = $('#mySelectBox option:selected');

Answering the question .is(':selected')is what you are looking for:

回答这个问题.is(':selected')就是你要找的:

$('#mySelectBox option').each(function() {
    if($(this).is(':selected')) ...

The non jQuery (arguably best practice) way to do it would be:

非 jQuery(可以说是最佳实践)的方法是:

$('#mySelectBox option').each(function() {
    if(this.selected) ...

Although, if you are just looking for the selected value try:

虽然,如果您只是在寻找选定的值,请尝试:

$('#mySelectBox').val()

If you are looking for the selected value's text do:

如果您正在寻找所选值的文本,请执行以下操作:

$('#mySelectBox option').filter(':selected').text();

Check out: http://api.jquery.com/selected-selector/

退房:http: //api.jquery.com/selected-selector/

Next time look for duplicate SO questions:

下次寻找重复的 SO 问题:

Get current selected optionor Set selected optionor How to get $(this) selected option in jQuery?or option[selected=true] doesn't work

获取当前选定的选项设置选定的选项如何在 jQuery 中获取 $(this) 选定的选项?选项 [selected=true] 不起作用

回答by gdoron is supporting Monica

You can get the selected option this way:

您可以通过以下方式获取所选选项:

$('#mySelectBox option:selected')...

LIVE DEMO

现场演示

But if you want to iterate all the options, do it with this.selectedinstead of this.isCheckedwhich doesn't exist:

但是,如果您想迭代所有选项,请使用不存在的选项this.selected代替this.isChecked

$('#mySelectBox option').each(function() {
    if (this.selected)
       alert('this option is selected');
     else
       alert('this is not');
});

LIVE DEMO

现场演示

Update:

更新:

You got plenty of answers suggesting you to use this:

你得到了很多建议你使用它的答案:

$(this).is(':selected')well, it can be done a lot faster and easier with this.selectedso why should you use it and not the native DOM element method?!

$(this).is(':selected')好吧,它可以更快更容易地完成,this.selected那么为什么要使用它而不是原生 DOM 元素方法呢?!

Read Know Your DOM Properties and Functionsin the jQuerytag info

阅读标签信息中的了解您的 DOM 属性和功能jQuery

回答by veeTrain

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

如果您不熟悉或不习惯is(),您可以检查 的值prop("selected")

As seen here:

如这里所见

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

编辑

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle updatedisplaying this action.

正如@gdoron 在评论中指出的那样,访问选项的 selected 属性的更快、最合适的方法是通过 DOM 选择器。这是显示此操作的小提琴更新

if (this.selected == true) {

appears to work just as well! Thanks gdoron.

似乎也能正常工作!谢谢格多伦。

回答by Amir

You can use this way by jquery :

您可以通过 jquery 使用这种方式:

$(document).ready(function(){
 $('#panel_master_user_job').change(function () {
 var job =  $('#panel_master_user_job').val();
 alert(job);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="job" id="panel_master_user_job" class="form-control">
                                    <option value="master">Master</option>
                                    <option value="user">User</option>
                                    <option value="admin">Admin</option>
                                    <option value="custom">Custom</option>
                                </select>

回答by Masoud Darvishian

Consider this as your select list:

将此视为您的选择列表:

<select onchange="var optionVal = $(this).find(':selected').val(); doSomething(optionVal)">

                                <option value="mostSeen">Most Seen</option>
                                <option value="newst">Newest</option>
                                <option value="mostSell">Most Sell</option>
                                <option value="mostCheap">Most Cheap</option>
                                <option value="mostExpensive">Most Expensive</option>

                            </select>

then you check selected option like this:

然后你检查选定的选项是这样的:

function doSomething(param) {

    if ($(param.selected)) {
        alert(param + ' is selected!');
    }

}

回答by Mouna Cheikhna

use

 $("#mySelectBox option:selected");

to test if its a particular option myoption:

测试它是否是一个特定的选项myoption

 if($("#mySelectBox option:selected").text() == myoption){
          //...
 }

回答by Sergey Onishchenko

In my case I don't know why selected is always true. So the only way I was able to think up is:

就我而言,我不知道为什么 selected 总是正确的。所以我能想到的唯一方法是:

var optionSelected = false;
$( '#select_element option' ).each( function( i, el ) {
    var optionHTMLStr = el.outerHTML;

    if ( optionHTMLStr.indexOf( 'selected' ) > 0 ) {
        optionSelected = true;
        return false;
    }
});

回答by Adam

If you only want to check if an option is selected, then you do not need to iterate through all options. Just do

如果您只想检查是否选择了某个选项,则无需遍历所有选项。做就是了

if($('#mySelectBox').val()){
    // do something
} else {
    // do something else
}

Note: If you have an option with value=0 that you want to be selectable, you need to change the if-condition to $('#mySelectBox').val() != null

注意:如果您有一个 value=0 的选项想要可选,则需要将 if-condition 更改为 $('#mySelectBox').val() != null

回答by dimpiax

If you need to check option selected state for specific value:

如果您需要检查特定值的选项选择状态:

$('#selectorId option[value=YOUR_VALUE]:selected')

回答by Abhishek Pratap Singh

If you want to check selected option through javascript

如果您想通过 javascript 检查所选选项

Simplest method is add onchange attribute in that tag and define a function in js file see example if your html file has options something like this

最简单的方法是在该标签中添加 onchange 属性并在 js 文件中定义一个函数,请参见示例,如果您的 html 文件有这样的选项

 <select onchange="subjects(this.value)">
               <option>Select subject</option>
               <option value="Computer science">Computer science</option>
               <option value="Information Technolgy">Information Technolgy</option>
               <option value="Electronic Engineering">Electronic Engineering</option>
               <option value="Electrical Engineering">Electrical Engineering</option>
 </select>

And now add function in js file

现在在js文件中添加函数

function subjects(str){
    console.log(`selected option is ${str}`);
}

If you want to check selected option in php file

如果要检查 php 文件中的选定选项

Simply give name attribute in your tag and access it php file global variables /array ($_GET or $_POST) see example if your html file is something like this

只需在您的标签中提供 name 属性并访问它 php 文件全局变量 /array ($_GET 或 $_POST) 如果您的 html 文件是这样的,请参见示例

<form action="validation.php" method="POST">
             Subject:<br>
            <select name="subject">
               <option>Select subject</option>
               <option value="Computer science">Computer science</option>
               <option value="Information Technolgy">Information Technolgy</option>
               <option value="Electronic Engineering">Electronic Engineering</option>
               <option value="Electrical Engineering">Electrical Engineering</option>
            </select><br>

         </form>

And in your php file validation.php you can access like this

在你的php文件validation.php中,你可以像这样访问

$subject = $_POST['subject'];
echo "selected option is $subject";