簡體   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