2012-03-16 43 views
3

如何在點擊元素或其容器時(取消)檢查無線電輸入元素?如何在點擊時切換無線電輸入元素的檢查狀態?

我曾嘗試下面的代碼,但它不會取消收音機。

HTML:

<div class="is"> 
    <label><input type="radio" name="check" class="il-radio" /> Is </label> 
    <img src="picture" /> 
</div> 

的jQuery:

$(".is label, .is ").click(function() { 
    if (!$(this).find(".il-radio").attr("checked")) { 
     $(this).find(".il-radio").attr("checked", "checked"); 
    } else if ($(this).find(".il-radio").attr("checked") == "checked") { 
     $(this).find(".il-radio").removeAttr("checked"); 
    } 
}); 
+1

你爲什麼不只是使用標籤在其原來的形式? http://www.w3schools.com/tags/tag_label.asp – 2012-03-16 13:27:47

+2

@OriesokVlassky:因爲這需要每個輸入控件都有一個ID,以便標籤引用它。 ''是有效的HTML;它應該工作。 – cHao 2012-03-16 13:31:35

+0

檢查http://stackoverflow.com/questions/2117538/jquery-how-to-uncheck-a-radio-button – 2012-03-16 14:04:09

回答

6

Y你必須防止默認行爲。目前發生以下情況:

  1. click容器事件火災(div.is)。
  2. click事件觸發標籤。
  3. 由於你的函數切換狀態,並且事件監聽器被調用了兩次,結果是沒有任何事情發生。

修正碼(http://jsfiddle.net/nHvsf/3/):

$(".is").click(function(event) { 
    var radio_selector = 'input[type="radio"]', 
     $radio; 

    // Ignore the event when the radio input is clicked. 
    if (!$(event.target).is(radio_selector)) { 
     $radio = $(this).find(radio_selector); 
     // Prevent the event to be triggered 
     // on another element, for the same click 
     event.stopImmediatePropagation(); 
     // We manually check the box, so prevent default 
     event.preventDefault(); 
     $radio.prop('checked', !$radio.is(':checked')); 
    } 
}); 
$(".il-radio").on('change click', function(event) { 
    // The change event only fires when the checkbox state changes 
    // The click event always fires 

    // When the radio is already checked, this event will fire only once, 
    // resulting in an unchecked checkbox. 
    // When the radio is not checked already, this event fires twice 
    // so that the state does not change 
    this.checked = !this.checked; 
}); 
+0

你可以做到這一點,如果我點擊收音機它自己也會檢查它嗎? – funerr 2012-03-20 16:21:49

+0

現在圖片不會觸發選擇。 – funerr 2012-03-20 17:26:35

+0

@ agam360此前,'event.target'屬性被用作參考。這是錯誤的,現在已經修復了。 – 2012-03-20 17:34:46

5

單選按鈕不取消,你需要使用一個複選框(類型= '複選框')

+0

你能給我正確的方式爲無線電這樣做呢? – funerr 2012-03-16 13:28:34

+2

單選按鈕通常只有在單擊具有相同「名稱」屬性的另一個單選按鈕時纔會被取消選中,這是基本的HTML – CKKiller 2012-03-16 13:30:19

+0

單選按鈕以這種方式工作。如果您想要「取消選中」行爲,您應該使用複選框 – MatuDuke 2012-03-16 13:31:11

0

僅使用HTML,相同的功能

<label for="rdio"><input type="radio" name="rdio" id="rdio" class="il-radio" /> Is </label> 
+0

當控件是標籤中唯一的控件時,不需要'for'屬性。 – cHao 2012-03-16 13:35:49

+0

但是我想要點擊它時自己選擇的div ... – funerr 2012-03-16 13:36:12