开发者

Event for $('input[type=radio]:checked')

This is my jQuery script:

$("input[type=radio]:checked").live("click", function() {
    $(this).attr("checked",false);
});

I want to make all my radio button can be checked and unchecked. The code suppose to trigger ONLY when checked radio being clicked. But somehow, any ra开发者_JS百科dio click (whether it's checked or not) will trigger this event. It's as if the browser will check the radio first and then run my script.

If I alert($("input[type=radio]:checked").size()), it gave me the correct count.

I'm testing the code in FF4 but I hope the solution can cater for IE as well.

Ok, since my question seems confusing, this is the working code for what I want, BUT it requires additional custom attribute which I hope can avoid.

<input type="radio" name="group1" value="1" isChecked="false"/>
<input type="radio" name="group1" value="2" isChecked="false"/>
<input type="radio" name="group1" value="3" isChecked="false"/>

<script>

$(document).ready(function(){
    $("radio").click(function(){
        if($(this).attr("isChecked")=="false"){
            $(this).attr("isChecked","true");
            $(this).attr("checked",true);
        }
        else{
            $(this).attr("isChecked","false");
            $(this).attr("checked",false);
        }
    });
});

</script>


This isn't really the way that radio buttons are intended to be used. It seems like you are trying to create an input control that's somewhere between a radio button and a checkbox.

There are a couple of approaches you could take:

1) Use a separate button to clear the radio buttons:

The HTML:

<input id="clearRadios" type="button">Clear</input>

The jQuery:

$('#clearRadios').click(function() {
    // use attr only if you're using an older version of jQuery
    $('input[type=radio]').prop('checked', false);
});

2) Use checkboxes rigged to work like radio buttons:

var $chkboxes = $('input[type=checkbox]');
$chkboxes.click(function() {
    var currChkbox = this;
    $chkboxes.each(function() {
        if (this !== currChkbox) {
            $(this).prop('checked', false);
        }
    });      
});

If it were me, I'd probably go with the first option in most circumstances.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜