我有很多单选按钮从我的数据库中获取值,如果设置为“1”,我会选中单选按钮.
如果选中单选按钮,并且用户再次单击它,我仍然希望能够清除此按钮.有没有人有想法?
dio1" type="radio"PHP if($radio1==1){echo " checked";} ?>>
dio2" type="radio"PHP if($radio1==2){echo " checked";} ?>>
Varun Malhotra的答案略有修改:
我改变了2行代码,对我来说效果更好.但总的来说,Varun的答案是完美的!
$('input[type="radio"]').click(function(){
var $radio = $(this);
// if this was prevIoUsly checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked',false);
$radio.data('waschecked',false);
}
else
{
$radio.prop('checked',true);
$radio.data('waschecked',true);
}
// remove was checked from other radios
$radio.siblings('input[type="radio"]').data('waschecked',false);
});
最佳答案
我建议添加一个自定义属性来跟踪每个无线电的先前状态,如下所示:
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was prevIoUsly checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked',false);
$radio.data('waschecked',false);
}
else
$radio.data('waschecked',true);
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked',false);
});
});
dio" name="rad" id="Radio0" checked="checked" data-waschecked="true" />
更新:
$(function(){
$('input[name="rad"]').click(function(){
var $radio = $(this);
// if this was prevIoUsly checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked',false);
$radio.data('waschecked',false);
}
else
$radio.data('waschecked',true);
// remove was checked from other radios
$radio.siblings('input[type="radio"]').data('waschecked',false);
});
});