2014-01-31 56 views
0

我想驗證我的按鈕時,如果不選中它將顯示錯誤的單選按鈕,但如果我們檢查,它會得到按鈕的id我們檢查。我嘗試如下代碼:jquery當提交按鈕需要驗證單選按鈕並獲取單選按鈕的編號

HTML:

<div class="radio"> 
    <label> 
     <input type="radio" name="chk" id="chk1" class="chk"/>abcd 
    </label> 
</div> 
<div class="radio"> 
    <label> 
     <input type="radio" name="chk" id="chk2" class="chk" /> 
     efg 
    </label> 
</div> 
<input type="button" value="Visualiser le résultat..." id="btnresult" class="btn"/> 

的Jquery:

$('#btnresult').on('click',function(){ 
         if (! $('input.chk').is(':checked')){ 
          alert('not check.'); 
         } 
         else if($('input.chk').is(':checked')) { 
          var getid = $(this).parent().find(".chk").attr('checked', true).attr('id'); 

          alert(getid); 

         } 

        }); 

我的問題是:我能得到的只有單選按鈕chk1的第一個ID,當我檢查其他無線按鈕。

回答

1

要獲得檢查單選按鈕

var getid = $('input.chk:checked').attr('id'); 

$(this).parent().find(".chk").attr('checked', true).attr('id')的ID將返回與父元素中類.chk爲第一要素,這將永遠是第一無線電元素的ID - 而不是一個檢查

如果你想在更具體的搜索,然後使用

var getid = $(this).parent().find(".chk:checked").attr('id'); 
1
$("#btnresult").click(function() { 
    if(!$("input.chk:checked").length) alert("Not checked"); 
    else alert($("input.chk:checked").attr("id")); 
});