我有一個HTML格式的表單,它有幾個選擇元素,最好的方式是通過這樣的方式對它們進行驗證,使得沒有兩個選擇元素可以具有相同的值,驗證函數應該觸發select,所以它可以檢查是否有任何選擇具有相同的選項值,如果是的話提醒一些事情,我可以得到一個解釋如何在JavaScript中寫這個?多重選擇驗證
謝謝
這裏是一點HTML代碼,我想驗證:
<form name="forma" action="" method="POST">
<select name="sel1">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
<select name="sel2">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
<select name="sel3">
<option>Please select</option>
<option>brand1</option>
<option>brand2</option>
<option>brand3</option>
</select>
</form>
這裏是小幅調整的解決方案,但是這是它:
var selectTest = function() {
var i, j;
sels = [document.getElementById("sel1"), document.getElementById("sel2"), document.getElementById("sel3")];
for (i = 0; i < sels.length; i += 1) {
for (j = i + 1; j < sels.length; j += 1) {
if(sels[i].value != "Please select")
{
if (sels[i].value === sels[j].value) {
alert("Selected values must be different");
return;
}
}
}
}
};
特別TNX到austin cheney,感謝所有發佈和參與的人。
我喜歡你的代碼非常..有輕微問題..選擇具有相同的值,所以每當我改變第一個選擇的值..我得到的錯誤信息..是否有可能避免只是..否則偉大的代碼.. – ant 2009-11-20 12:14:49
爲什麼「不使用名稱屬性」聲明? OPs代碼在'
我會建議在提交時執行該功能。因此,只需將的onsubmit添加到開頭的表單標籤:的onsubmit =「selTest()」 – 2009-11-20 12:28:56