5つ以上のオプションがある複数の選択リストがあり、ユーザーが選択したオプションの選択数を数えたいです。
Javaスクリプトを使用してそれを行う方法は?
次のことを試しましたが、うまくいきませんでした。
var x = document.getElementById("preference").count;
前もって感謝します。
5つ以上のオプションがある複数の選択リストがあり、ユーザーが選択したオプションの選択数を数えたいです。
Javaスクリプトを使用してそれを行う方法は?
次のことを試しましたが、うまくいきませんでした。
var x = document.getElementById("preference").count;
前もって感謝します。
foo
はselectのIDであると想定します。
通常のjavasriptを使用する場合:
var options = document.getElementById('foo').options, count = 0;
for (var i=0; i < options.length; i++) {
if (options[i].selected) count++;
}
jQueryを使用する場合:
var count = $('#foo option:selected').length;
これを試して、ユーザーが選択した複数の選択ボックスとその選択した名前を取得できます。このリンクを試してくださいhttp://jsfiddle.net/N6YK8/8/
function getCount(){
var comboBoxes = document.querySelectorAll("select");
var selected = [];
for(var i=0,len=comboBoxes.length;i<len;i++){
var combo = comboBoxes[i];
var options = combo.children;
for(var j=0,length=options.length;j<length;j++){
var option = options[j];
if(option.selected){
selected.push(option.text);
}
}
}
alert("Selected Options '" + selected + "' Total Count "+ selected.length);
}
:selected
次のようにセレクターを使用します。
$('#example option:selected').length;
< IE8 が問題にならない場合は、ワンライナーdocument.querySelectorAll("option:checked")
で選択したすべてのオプションを取得できます。
function SelectPage(elem)
{
alert(elem);
}
<select id="page" name="section" onChange="SelectPage(this);" id="num">
<option value="">Select Section</option>
<option value="1">Page-1</option>
<option value="2">Page-2</option>
<option value="3">Page-3</option>
<option value="4">Page-4</option>
<option value="5">Page-5</option>
</select>