简体   繁体   中英

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");

DEMO

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"

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");
        $(this).val(this.checked?'Y':'N');
});

Working Demo

$('input.box1').this.prop('checked', true).val("T") it throw Uncaught error instead of this u can use $(this).prop('checked', true).val("T")
(function ($) {
   var count = 0;
   $(document).ready(function () {
      $('input.box1').on('change', function(e) {
          $('input.box1').not(this).prop('checked', false).val("N");
          $(this).prop('checked', true).val("T");

          console.log($("#chkBox1").val(), $("#chkBox2").val());
       });
   });
})(jQuery);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM