简体   繁体   中英

how to check/uncheck a checkbox on keyup

I have been trying to make a script that checks and unchecks a checkbox when I press the 'c' key but it doesn't work.

$(document).keyup(function(e){
  if(e.which == 67){
    if($('#main').css('opacity') == 0) {
    if ($('#cHideChat').attr('checked')) {
    $('#cHideChat').prop('checked', false);
    }
    else {
    $('#cHideChat').prop('checked', true);
      }
    }
  }
});

You can do it like this

 $(document).on('keyup', function(e) { var checkBox = $('#cHideChat') if ($('#main').css('opacity') == 0) { if (e.which == 67) checkBox.prop("checked", !checkBox.prop("checked")); } }); 
 #main { opacity: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" name="" id="cHideChat"> <div id="main"></div> 

You need to check for prop like so:

$(document).keyup(function(e){
  if(e.which == 67){
    if($('#main').css('opacity') == 0) {
    if ($('#cHideChat').prop('checked')) {  // check for prop, not attr
    $('#cHideChat').prop('checked', false);
    }
    else {
    $('#cHideChat').prop('checked', true);
      }
    }
  }
});

I think the issue isn't related to the jQuery. Although Nenad and Sandeep provided better way to achieve what you want, the jQuery code should run fine. However I see two other issues:

First of all, key code 67 corresponds to the upper 'C', thus your code does not respond to lower 'c' presses. The key code for lower 'c' is 99. Second, there is no attribute "checked". It's a property and you should query it through .prop("checked") instead .attr("checked") . The latter returns undefined which corresponds to false and your condition is never met. So just edit your code as Nenad Vracar suggested, but make sure to check for key code 99 like so:

if (e.which == 67 || e.which == 99) {
    checkBox.prop("checked", !checkBox.prop("checked"));
}

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