1

我在页面上有 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;
}

看起来很简单。想法?

4

4 回答 4

3

在 jQuery 中,您可以使用:selected选择器来获取所选的全部选项。这个数字与选择本身的数量相匹配:

if ($("select").length === $("option:selected").length) {
  // they match
}
于 2010-02-19T14:13:25.790 回答
2

我想验证这两个选择框都有一个选定的选项

(非multipleselect不可能没有选定的选项!如果你没有selected在其中一个上声明option,浏览器会自动选择第一个选项。

所以:return true;:-)

如果你想有一个“未选择”的初始状态,你必须option为它包含一个 no-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;
});
于 2010-02-19T15:11:54.640 回答
1

您可以为此使用: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
}
于 2010-02-19T14:10:01.460 回答
0
 function checkSelects() {
        return $("select :selected").length == $("select").length;
    }

alert(checkSelects());
于 2010-02-19T14:17:41.647 回答