2013-09-25 223 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); 

     }); 
相关问题