Reputation: 1951
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);
}
Upvotes: 2
Views: 5978
Reputation: 8552
If i understand your requirement correctly pls check this
$(document).ready(function () {
$('input:checkbox[id=mycheckbox]').keypress(function (event) {
event.stopPropagation();
var keycode = getKeyCodeFromEvent(event);
if (keycode == 13) {
clickCheckBox(this);
}
});
});
function clickCheckBox(box) {
$(box).trigger('click');
}
function getKeyCodeFromEvent(event) {
return (event.keyCode ? event.keyCode : event.which);
}
Upvotes: 3
Reputation: 852
I had needed same thing in Angulajs and found a solution. Thinking that it might help others as there no other question was raised for Angular I am sharing my code here:
angular.module('app', [])
.directive('input', function() {
return {
restrict: 'E', // Only search input element
link: function(scope, elm, attr) {
if (attr.type === 'checkbox') { //filtered out the checkbox only
elm.on('keypress', function(event){
if(event.keyCode === 13){
event.preventDefault();
elm.trigger('click');
scope.$apply();
}
});
}
}
};
});
hope it will help you those who are seeking for the same solution in AngularJS...
Upvotes: 1
Reputation: 1287
There is a problem in your code here
function clickCheckBox(box){
var $box = $(box);
if($box.attr('checked'))
$box.attr('checked',false);
else
$box.attr('checked',true);
}
.attr()
doesn't accepts boolean values . Go for prop()
if you are using jQuery 1.6 or above that
Upvotes: 1
Reputation: 1934
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..
Upvotes: 2
Reputation: 26848
This code works, tested on Chrome 30
<html>
<body>
<input type='checkbox' id='mycheckbox' />
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$('#mycheckbox').keydown(function(ev){
if(ev.keyCode == 13) $(ev.target).click();
})
});
</script>
</body>
</html>
Upvotes: 2