2015-05-07 83 views
1

我有一個按以下方式綁定到複選框的單選按鈕列表。

1)當複選框被選中,單選按鈕被啓用,並具有檢查一個默認按鈕(比如值= 1)(只有一個單選按鈕可以被選擇出三個)

2)當該複選框的未選中,單選按鈕被禁用,其選擇屬性被刪除。由於JQuery函數,單選按鈕默認選中不工作

我面臨的問題是,由於以下HTML和JQuery代碼,頁面加載(值= 1)上單選按鈕的默認選擇不起作用。我無法識別錯誤。有人可以幫忙嗎?

$('#mailcheck').change(function() { 
 
    $('input[name="freq"]').prop('disabled', !this.checked); 
 
    $('input[name="freq"]').removeAttr('checked'); 
 
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<label id="notcheck"> 
 
    <input type="checkbox" id="mailcheck" checked="checked">I want to receive an email notification of ads uploaded on my college marketplace 
 
</label> 
 
<br> 
 

 
<ul> 
 
    <li> 
 
    <label> 
 
     <input type="radio" name="freq" value="1" id="freqradio" checked="checked">Daily</label> 
 
    </li> 
 
    <li> 
 
    <label> 
 
     <input type="radio" name="freq" value="3" id="freqradio">Every 3 days</label> 
 
    </li> 
 
    <li> 
 
    <label> 
 
     <input type="radio" name="freq" value="7" id="freqradio">Weekly</label> 
 
    </li> 
 
</ul>

+0

不要在最後調用'.change()'。這是運行處理程序,並刪除所有'checked'屬性。 – Barmar

+0

爲什麼要刪除禁用的無線電輸入的'checked'屬性?如果他們被禁用,他們將不會被提交給服務器,並且如果有人不小心取消選中,他(通常)會讓該用戶不得不重新檢查某些內容。特別是如果在整個表單中重複使用相同的功能。 –

+0

這有效,但只是部分。每當複選框被選中時,單選按鈕應該被選中。我如何確保? –

回答

5

這是一個粗略的工作版本:

$('#mailcheck').change(function(){ 
 
    if($(this).is(':checked')) { 
 
     $('input[name="freq"]').prop('disabled', false).first().prop('checked', true); 
 
    } else { 
 
     $('input[name="freq"]').prop('disabled', true).prop('checked', false); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<label id="notcheck"> 
 
<input type="checkbox" id="mailcheck" checked="checked" >I want to receive an email notification of ads uploaded on my college marketplace 
 
</label><br> 
 

 
    <ul> 
 
    <li><label><input type="radio" name="freq" value="1" id="freqradio1" checked="checked">Daily</label></li> 
 
    <li><label><input type="radio" name="freq" value="3" id="freqradio2">Every 3 days</label></li> 
 
    <li><label><input type="radio" name="freq" value="7" id="freqradio3">Weekly</label></li> 
 
    </ul>

附:該ID必須具有唯一的值

+1

爲什麼複製到jsfiddle而不是在這裏使用堆棧片段? – Barmar

+0

@Barmar - 我不知道那個:),我編輯了我的答案 – nevermind

+0

完美的作品。謝謝! –