2013-09-25 169 views
-1

我試圖取消選中一個單選按鈕,如果它被選中,同樣檢查一個單選按鈕,如果它沒有選中。但是,它總是在說它沒有被檢查。jquery檢查單選按鈕是否被選中

這裏是我的代碼:

$('input[type=radio]').on('click', function() { 
    if ($(this).attr('checked') == 'checked') { 
     $(this).attr('checked', false); 
    } else { 
     $(this).attr('checked', true); 
    } 
}); 

上面的代碼總是打,如果第一部分。我也試着

$(this).is(':checked') 

$(this).val() 

$(this).attr('checked') == true 

,但似乎沒有奏效。

我該如何得到這個工作?

+1

你確定你不想要複選框嗎?這似乎違背了單選按鈕的正常使用。 –

+0

不,因爲有了複選框,您可以選擇多個選項。我想選擇0或1選項。這樣用戶可以撤消他們的選擇,如果他們想要的話。 – socketman

+0

我有一個可用的例子,向下滾動到我的答案 – Aaron

回答

0

我不知道爲什麼,這收到的反對票。單選按鈕的使用方式使得您可以有0個或1個選項可供選擇,如果需要選擇0個或多個選項,則複選框列表是。但是如果你想撤銷一個可選問題的單選按鈕選擇呢?

我通過在稱爲「數據檢查」的單選按鈕上創建另一個屬性來解決此問題。

下面是執行:

$('input[type=radio]').on('click', function() { 
    var radioButton = $(this); 
    var radioButtonIsChecked = radioButton.attr('data-checked') == 'true'; 

    // set 'checked' to the opposite of what it is 
    setCheckedProperty(radioButton, !radioButtonIsChecked); 

    // you will have to define your own getSiblingsAnswers function 
    // as they relate to your application 
    // but it will be something similar to radioButton.siblings() 
    var siblingAnswers = getSiblingAnswers(radioButton); 

    uncheckSiblingAnswers(siblingAnswers); 
}); 

function uncheckSiblingAnswers(siblingAnswers) { 
    siblingAnswers.each(function() { 
     setCheckedProperty($(this), false); 
    }); 
} 

function setCheckedProperty(radioButton, checked) { 
    radioButton.prop('checked', checked); 
    radioButton.attr('data-checked', checked); 
} 

在頁面加載,數據覈對屬性設置爲true或false,這取決於它是否已被選中。

$(document).ready(function() { 
    $('input[type=radio]').each(function() { 
     var radioButton = $(this); 
     var radioButtonIsChecked = radioButton.attr('checked') == 'checked'; 

     setCheckedProperty(radioButton, radioButtonIsChecked); 
    }); 
}); 
0

您需要刪除選中的屬性以取消選中,並添加屬性以檢查單選按鈕。不要將值分配給它:

<input type="radio" name="radio1"> 
<input type="radio" name="radio1" checked> 

使用:

$(this).addAttr("checked") 
$(this).removeAttr("checked") 
0

這應該永遠不會失敗,但它是一個不同的方法。 定位父母,並返回檢查哪個無線電,而不是全部查看。 只是一個想法

var myRadio; 
$('#radioParent input:radio').click(function() { 
    myRadio = $(this).attr('id'); 
    //console.log(myRadio); 
    //return myRadio; 
}); 
1

這裏是fiddle希望這個麻煩全部幫助:

<input type="radio" name="" value="1000" align="middle" id="private_contest">1000 is the value<br> 

<input type="radio" name="" value="2000" align="middle" id="private_contest">2000 is the value 

和有關jQuery是:

$('input[type=radio]').on('click', function() { 

       $(this).siblings().prop('checked', true); 
       $(this).prop('checked', false); 

     }); 
相關問題