Adamo Adamo - 1 year ago 108
jQuery Question

Only one checkbox checked and values

I have small problem with checkboxes. Better way to do that is radio button but I must do that with checkboxes.

Here's the code:

$('input.box1').not(this).prop('checked', false).val("N");


and it's working because one of checkboxes is checked. But in input value is "true" for this two checkboxes. How Can I change that code to do that when I check checkbox other should have a "false" value.

I try something like this:

$('input.box1').on('change', function() {
$('input.box1').not(this).prop('checked', false).val("N");
$('input.box1').this.prop('checked', true).val("T");

but didn't work

-What I expect?
1.In example click first checkbox - value of that checkbox is "T" the second checkbox has value "N"
2. Click second checkbox - value of that checkbox is "T" the first checkbox has value "N"

Answer Source

You have error in your code at line $('input.box1').this.prop('checked', true).val("T");

Uncaught TypeError: Cannot read property 'prop' of undefined

That's because $('input.box1').this is undefined. SYNTAX ERROR.

Correct way to do this is simply using context this in change function :

$('input.box1').on('change', function() {
        $('input.box1').not(this).prop('checked', false).val("N");

Working Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download