Louie Miranda
Louie Miranda

Reputation: 1159

Dependent checkbox, do you think this can be simplified more?

I have the following code which is working, I was wondering if this can simplified more.

Demo: http://jsfiddle.net/TnpNV/8/

<form name="cbform">
<input type="checkbox" value="1" name="one" id="one" /> one<br />
<input type="checkbox" value="1" name="two" id="two" /> two
</form>​

<script>
$('#one, #two').click(function(event) {
    var checked = $(this).is(':checked');
    if (checked) {
        $('#one').attr('checked', true);
        $('#two').attr('checked', true);
    }
    else {
        $('#one').attr('checked', false);
        $('#two').attr('checked', false);
    }
});
</script>

It's basically a two checkbox that is dependent on each other. Jquery was used to check and uncheck them.

Regards

Upvotes: 0

Views: 2314

Answers (3)

Tats_innit
Tats_innit

Reputation: 34107

Compact most working DEMO http://jsfiddle.net/U5GfF/ or http://jsfiddle.net/U5GfF/3/

This is the least line version you can get for your code: i.e.

this.checked will return true and false and rest on click event prop will set checked property accordingly. :)

Hope this helps,

code

$("#one, #two").click(function() {
    $("input").prop('checked', this.checked);
});

or

$("#one, #two").click(function() {
    $("#one, #two").prop('checked', this.checked);
});

or

$("#one, #two").on('click', function() {
    $("#one, #two").prop('checked', this.checked);
});

Upvotes: 4

Oscar Jara
Oscar Jara

Reputation: 14187

Try this, just 2 lines :-)

Live Demo:

http://jsfiddle.net/TnpNV/15/

For jQuery modern versions:

$('#one, #two').on('click', function(e) {
  var prop = ($(this).is(':checked')) ? true : false;
  $('#one, #two').prop('checked', prop);
});​

For jQuery old versions (Because I saw in your jsFiddle that you are using jQuery 1.4.4 version) Also, this code will work in all versions.

$('#one, #two').click(function(e) {
  var prop = ($(this).is(':checked')) ? true : false;
  $('#one, #two').attr('checked', prop);
});

Upvotes: 1

Ram
Ram

Reputation: 144689

you can use prop() method:

$('#one, #two').click(function(event) { // or $("input:checkbox")
    if ($(this).is(':checked')) {
        $('#one, #two').prop('checked', true); // or $("input:checkbox")
    } else {
        $('#one, #two').prop('checked', false);
    }
});

Demo

Upvotes: 2

Related Questions