开发者

Automatically re-check a checkbox when I decheck another one

As a student, I am trying to learn some JQuery tricks. Here my HTML

<div id="EngineGroup" class="OptionGroupStyle">
    <div id="GS300"><input id="GS300Check" name="GS3开发者_如何学Go00Check" type="checkbox" disabled="disabled" checked="checked"/>V6 250ch</div>
    <div id="GS300Price">53.000 €</div>
    <div id="GS430"><input id="GS430Check" name="GS430Check" type="checkbox"/>V8 283ch</div>
    <div id="GS430Price">58.000 €</div>
    <div id="GS450H"><input id="GS450HCheck" name="GS450HCheck" type="checkbox"/>V8 Hybride 345ch</div>
    <div id="GS450HPrice">63.000 €</div>
</div>

GS300 is the default option.

  • When "GS430Check" is checked -> GS300 and GS450H are unchecked
  • When "GS450HCheck" is checked -> GS300 and GS430 are unchecked

It's ok for that with

$("#GS430Check").click(function() {
        $("input[name=GS300Check]").attr("checked",false);
        $("input[name=GS450HCheck]").attr("checked",false);
});

same for GS450H

But how can I can automatically re-check GS300 by default when I uncheck/unselect GS430 or GS450H when they are already checked ? I couldn't find something like ondeCheck/ondeSelect in JQuery, did I miss something or am I a real noob who can't understand something really simple ?

Edit :

$("#EngineGroup input").click(function() {
    if (!$("#EngineGroup input:checked").length) {
        $("#EngineGroup input:first").attr("checked", true);
    }
});

is working great :)


If you can't change the HTML, then I'd suggest that it might be easier to simply save the current state of a checkbox on a click, then uncheck all the boxes and flip the state of the clicked checkbox to the opposite of it's previous state. If there are still none checked after this, you should simply check the default checkbox. This way you could do it all in a single handler instead of having a handler per checkbox.


You should look into using the is() method in jQuery to see if something is checked:

if ($('#GS430Check').is(':checked')) {
  // do stuff...
}


Forget jQuery's attr() and is() for getting and setting the checkedness of a checkbox. They are hugely overcomplicated and inefficient for this task. Instead, use the much simpler boolean checked property of the checkbox element:

if ( $('#GS430Check')[0].checked ) {
    $('#GS300Check')[0].checked = true;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜