Reputation: 45
I am using this simple script provided from a friendly lad in #javascript to uncheck radio buttons:
$('.feed').on('click', 'input[type=radio]', function() {
var myParent = $(this).closest('div');
var ref = $(this);
if( myParent.data('val') == $(this).val() ){
var ref = myParent.find('.none input');
ref.prop('checked',true);
}
myParent.data('val',ref.val() )
});
Everything works fine, see this fiddle, but when I add the attribute 'checked' to one radio button you will actually have to click twice before you can uncheck it, see this fiddle. This got me thinking, is setting 'checked' as an attribute actually equal to checking the radio button by hand? Or why am I failing this?
Upvotes: 0
Views: 641
Reputation: 28611
This has nothing to do with adding an an attribute vs clicking, it's the additional code, specifically this line:
if (myParent.data('val') == $(this).val() ){
which says, if you clicked this before, then turn it off.
However, you're not telling the code that you've already (virtually) "clicked" it.
You can do this by adding the initial value to the 'myParent', one way is to add it to the html:
<div data-val='1'>
Updated fiddle: https://jsfiddle.net/8jh2k8u8/4/
An alternative is to initialise the parent via code by finding the radio that is selected (:checked
):
var startup = $(".feed input[type=radio]:checked").first();
if (startup.length) {
startup.closest("div").data("val", startup.val())
}
Updated fiddle: https://jsfiddle.net/8jh2k8u8/5/
Upvotes: 1