すべての選択ボックスがJavaScriptやjQueryのまたはを介して、選択されたオプション...を持っていることをどうやって確認することができますか?
-
21-09-2019 - |
質問
私はそれらのオプションの可変数のページに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
}
他のヒント
私は、これらの選択ボックスの両方が選択されたオプション
を持っていることを確認したいと思います
これはのないの選択オプションを持っている(非multiple
)select
ボックスのことはできません!あなたが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());