2013-10-08 152 views
0

我需要一個警報來顯示何時沒有選中單選按鈕。Javascript單選按鈕警報的問題

HTML代碼:

<tr> 
<td><input id="Radio1" name="delivery" value="M" type="radio">M</td> 
</tr> 
<tr> 
<td><input id="Radio2" name="delivery" value="P" type="radio">P</td> 
</tr> 
<tr> 
<td><input id="Radio3" name="delivery" value="S" type="radio">S</td> 
</tr> 

的Javascript:

 deliveryChecked = "" 
    for (i = 0; i < f.deliveryChecked; i++) { 
     if (f.deliveryChecked[i].checked) { 
      deliveryChecked = f.delivery[i].value 
      break 
     } 
    } 

      if (deliveryChecked == "") { 
      alert("You did not make a delivery selection!") 
     return false 
    } 
+0

什麼是 「F」?你期望「f.deliveryChecked」是什麼? – Pointy

+0

捕獲下一個用戶生成的事件(通常點擊一個提交按鈕),並檢查是否沒有選中單選按鈕。關鍵是:將一個事件處理程序綁定到Submit(或Next/Continue/Go/Whatever)按鈕 – gibberish

+0

哦 - 看起來你剛剛有一個錯字 - 「f.deliveryChecked」應該只是「f.delivery」。 – Pointy

回答

0

HTML:

<form onsubmit="return validate(this)"> 
    <input id="Radio1" name="delivery" value="M" type="radio" /> 
    <input id="Radio2" name="delivery" value="P" type="radio" /> 
    <input id="Radio3" name="delivery" value="S" type="radio" /> 
    <input type="submit" /> 
</form> 

JS:

function validate(frm){ 
    var atLeastOneChecked=false; 
    [].forEach.call(frm.delivery,function(input){ 
     atLeastOneChecked=atLeastOneChecked? 
      true 
       : 
      input.checked; 
    }); 
    if(!atLeastOneChecked){ 
     alert("You did not make a delivery selection!"); 
     return false; 
    } 
    return true; 
}