すべての選択ボックスがJavaScriptやjQueryのまたはを介して、選択されたオプション...を持っていることをどうやって確認することができますか?

StackOverflow https://stackoverflow.com/questions/2296757

質問

私はそれらのオプションの可変数のページに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セレクタを使用することができます。

:アウトこの番号は選択の自身の数と一致します
if ($("select").length === $("option:selected").length) {
  // they match
}

他のヒント

  

私は、これらの選択ボックスの両方が選択されたオプション

を持っていることを確認したいと思います

これはのないの選択オプションを持っている(非multipleselectボックスのことはできません!あなたがselected秒のいずれかにoptionを宣言していない場合は、ブラウザが自動的に最初のオプションを選択します。

ですから:return true;: - )

:あなたが「非選択」初期状態を持つようにしたい場合は、

、あなたはそれのためノーオプションoption、通常は最初のものを含める必要があるだろう

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

そして、あなたはその1つの異なるオプションはどちらかと言うことによって、選択されているかどうかを確認することができます:

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

それとも、あなたは有効な値として空の文字列を使用する場合があります場合は、あなただけ選択したオプションの指標で見ることができます:

$('select').each(function() {
    if (this.selectedIndex===0)
        allSelected= false;
});
あなたは使用することができます。このために選択されたセレクタ

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帰属
所属していません StackOverflow
scroll top