Reputation: 1159
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
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
Reputation: 14187
Try this, just 2 lines :-)
Live Demo:
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