2013-05-10 141 views
-1

我希望檢查是否使用javascript選擇了我的多個下拉列表中的任何內容。JavaScript元素驗證

<select name="id" id="id" size=22 multiple > 

並且如果任何複選框被選中

<input type="checkbox" name="inst" class="asa" value="inst1"> 
<input type="checkbox" name="inst" class="asa" value="inst2"> 
+0

你可以使用jQuery嗎? – sergserg 2013-05-10 04:00:38

回答

1

試試這個代碼

DEMO

var selectVal = document.getElementById('id'); 
var selectCount = 0; 
var values = []; 
for (var i = 0; i < selectVal.options.length; i++) { 
    if (selectVal.options[i].selected) { 
    selectCount++; 
    values.push(selectVal.options[i].value); 
    } 
} 

的複選框

<input type="checkbox" name="inst" class="asa" id="check1" value="inst1"> 
<input type="checkbox" name="inst" class="asa" id="check2" value="inst2"> 

var check1 = document.getElementById("check1").checked; 
alert(check1); 
var check2 = document.getElementById("check2").checked; 
alert(check2); 
+0

謝謝!不知道會需要循環 – user2285115 2013-05-10 06:56:51

0

嘗試

var select = document.getElementById('id'); 

var selected = []; 
for(var i =0 ; i < select.options.length; i++){ 
    if(select.options[i].selected){ 
     selected.push(select.options[i].value); 
    } 
} 
if(selected.length == 0){ 
    alert('not selected'); 
} 

演示:Fiddle

0

HTML:

<select name="id" id="three" size=22 multiple> 
    <option value="thevalue">Option</option> 
</select> 

<select name="id" id="four" size=22 multiple> 
    <option value="thevalue" selected="selected">Option</option> 
</select> 

JS:

var one = document.getElementById("one"); 
var two = document.getElementById("two"); 
var three = document.getElementById("three"); 

if(one.checked) 
    console.log("one = checked!"); 
else 
    console.log("one != checked"); 

if(two.checked) 
    console.log("two = checked!"); 
else 
    console.log("two != checked"); 

if(three.value) 
    console.log("something is selected in three!"); 
else 
    console.log("nothing is selected in three"); 

if(four.value) 
    console.log("something is selected in four!"); 
else 
    console.log("nothing is selected in four"); 

Fiddle包括複選框和選擇。

顯然這是一個非常詳細的例子,但是你可以修剪它以拿走你需要的東西。