Sanket Pipariya Sanket Pipariya - 10 days ago 5
Javascript Question

Enter Key Event on CheckBox in JQuery

I am novice in jquery implementation.. I need to apply enter key event on checkbox with id="mycheckbox" so that whenever i press enter key on checkbox it should be selected. What i have tried so far is below, but it seems not working.
Any suggestion is greatly appriciated.



$(document).ready(function(){
$('input:checkbox[id=mycheckbox]').keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
alert('keycode='+keycode+' pressed.');
if (keycode == 13) {
clickCheckBox(this);
}
event.stopPropagation();
});

$('input:checkbox[id=mycheckbox]').click(function(){
clickCheckBox(this);
});
});

function clickCheckBox(box){

var $box = $(box);
if($box.attr('checked'))
$box.attr('checked',false);
else
$box.attr('checked',true);

}



Answer

removed click event(you don't need it) and modified code little bit(used prop instead of attr)..

$(document).ready(function() {
     $('#mycheckbox').keypress(function(event) {
         var keycode = (event.keyCode ? event.keyCode : event.which);

         if (keycode == 13) {
             clickCheckBox(this);
         }
         event.stopPropagation();
     });
 });

 function clickCheckBox(box) {

     var $box = $(box);
     $box.prop('checked', !$box.prop('checked'));

 }

created jsfiddle for this and working fine..

http://jsfiddle.net/c2S5d/23/