2013-11-27 29 views
0

我有一個表單,其中包含的數據將被動態添加到我的表單中。一旦添加了數據,我想驗證一個單選按鈕的值(特別是如果單選按鈕已被選中),然後根據檢查哪個單選按鈕來做不同的事情。無法驗證預選的單選按鈕

目前,無論單選按鈕的狀態如何(即選中或未選中),我都無法這樣做。我總是收到警報(「Button is no checked」)。

代碼:

<!DOTYPE HTML> 
<html> 

<head> 
    <link type='text/css' rel='stylesheet' href='style.css'> 
    <!--jQuery Validation--> 
    <!--Loads JQuery and JQuery validate plugin--> 
    <script src="//code.jquery.com/jquery-1.9.1.js"></script> 
    <script type='text/javascript'> 
     $(document).ready(function() 
     { 


      function checkradio(radio) 
      { 

       if (radio.checked) 
       { 
        alert("no is checked"); 
       } 
       else 
       { 
        alert("no is not checked"); 
       } 

      } 

      function radiocheck() 
      { 

       checkradio($('#no')); 

      } 

      $('#submit1').click(function() 
      { 

       radiocheck(); 

      }) 


     }); 
    </script> 
</head> 

<body>  
    <input type='radio' id='yes' name='radiobutton' value='yes'>yes 
    <input type='radio' checked='checked' id='no' name='radiobutton' value='no'>no 
    <input type='button' id='submit1' name='submit' value='submit'>  
</body>  
</html> 
+1

檢查正確的檢查方法與jQuery http://stackoverflow.com/questions/2272507/find-out-if-無線電按鈕被檢查與jquery –

回答

1

您正在嘗試一個jQuery對象上使用本地DOM元素checked財產。

可以使用:

if(radio.is(':checked')); 

或本機的DOM元素傳遞給checkradio()而不是jQuery對象

checkradio($('#no')[0]); 
0
function checkradio(radio){ 

    if(radio.prop('checked')) 
    { 
     alert("no is checked"); 
    } 
    else 
    { 
     alert("no is not checked"); 
    } 

} 

OR

$('#submit1').click(function(){ 
    if($('#no').prop('checked')){ 
     alert("is checked"); 
    }else{ 
     alert("is not checked"); 
    } 
}) 
0

試試這個

checkradio($("input:radio[name=radiobutton]")); 
+0

ID選擇器更有效率。選擇器與問題無關。這個解決方案不會工作...將相同的對象傳遞給函數。 – charlietfl

0

改變你的代碼像

checkradio($("input[name='radiobutton']")); //This will give all radio buttons with name "radiobutton"

if()

添加radio.is(':checked')

FIDDLE