繁体   English   中英

如何通过JavaScript或JQuery或…来验证所有选择框是否都具有选定的选项?

[英]How can I verify that all select boxes have a selected option through JavaScript or JQuery or…?

我在页面上有2个选择框,其中有多个选项。

例如:

<fieldset>
    <label for="fizzwizzle">Select a Fizzwizzle</label>
    <select name="fizzwizzle" id="fizzwizzle" size="10">
        <option>Fizzwizzle_01</option>
        <option>Fizzwizzle_02</option>
        <option>Fizzwizzle_03</option>
        <option>Fizzwizzle_04</option>
    </select>
</fieldset>
<fieldset>
    <label for="fizzbaggot">Select a Fizzbaggot</label>
    <select name="fizzbaggot" id="fizzbaggot" size="10">
        <option>Fizzbaggot_01</option>
    </select>
</fieldset>

我想验证这两个选择框是否都具有选定的选项。 我最初的想法是仅使用JQuery,但似乎无法弄清楚该怎么做。 到目前为止,我的尝试都是徒劳的,但是我认为以下代码可以与缺少的链接一起使用。

function verify_selectboxen_selection() {
    var allSelected = true;

    $('select').each(function() {
      /* if select box doesn't have a selected option */
            allSelected = false;
            break;
    });

    if (!allSelected) {
        alert('You must select a Job and a Disposition File.');
    }
    return allSelected;
}

似乎很简单。 有什么想法吗?

在jQuery中,您可以使用:selected选择器来获取所选的全部选项。 此数字与select自身的数目匹配:

if ($("select").length === $("option:selected").length) {
  // they match
}

我想验证这两个选择框是否都具有选定的选项

(非multipleselect没有选择的选项是不可能的 如果您未在任何一个option上声明selected ,则浏览器将自动选择第一个选项。

所以: return true; :-)

如果要具有“未选择的”初始状态,则必须为其提供一个no-option option ,通常是第一个:

<select name="fizzbaggot">
    <option value="" selected="selected">(Select a fizzbaggot)</option>
    <option>foo</option>
    <option>baz</option>
    <option>bar</option>
</select>

然后,您可以通过以下方式检查是否选择了与该选项不同的选项:

$('select').each(function() {
    if ($(this).val()!=='')
        allSelected= false;
});

或者,如果您想使用空字符串作为有效值,则只需查看所选选项的索引即可:

$('select').each(function() {
    if (this.selectedIndex===0)
        allSelected= false;
});

您可以使用:selected选择器

var unselected = [] 
$('select').each(function(){
    if (0 == $(this).find('option:selected').length) {
        unselected.push(this.id);
    }
});

if (unselected.length != 0) {
    // unselected contains the ids of non-selected select boxes
}

或者,您可以使用val()检查它们的值。 这假定您有一个没有值的默认选项(即空字符串值)。

var unselected = [] 
$('select').each(function(){
    if ('' == $(this).val()) {
        unselected.push(this.id);
    }
});

if (unselected.length != 0) {
    // unselected contains the ids of non-selected select boxes
}
 function checkSelects() {
        return $("select :selected").length == $("select").length;
    }

alert(checkSelects());

暂无
暂无

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

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