when a user clicks the spacebar or backspace I need to create a variable that stores the action so I can use it to manipulate an array. I want the backspace to delete a value in an array and the spacebar to create a space. How can I do this?
Maybe this can help you:
$('body').keyup(function(e){
if(e.keyCode == 8){
// user has pressed backspace
array.pop();
}
if(e.keyCode == 32){
// user has pressed space
array.push('');
}
});
-
-
Yeah. You can also search for an element inside array, and delete that one. – Saeed Neamati Nov 22 '11 at 6:57
-
-
1Backspace key code is 8. To get the key code of any key on the keyboard, simply put an input element somewhere, bind to
keyup
event and write thee.keyCode
to the console (or alert it). – Saeed Neamati Nov 22 '11 at 7:16
try this
$(document).ready( function() {
$('#inputid').bind('keypress', function(e) {
if (e.which == 32){//space bar
alert('space');
}
if (e.which == 8) {//backspace
alert('back space');
}
});
});
Try this fiddle: http://jsfiddle.net/gSWwp/1/
I call the method e.preventDefault(); for ignore the default event associated to the keypress for a field. http://api.jquery.com/event.preventDefault/
It scrolled down the page! I wanted to use the space bar key to trigger a function as:
$("#org").on("keydown", function(e){
if(e.keyCode == 32){
my_func();//The function executes but the page is scrolled down
}
});
Now I have changed the code and added return false and it worked perfectly as I don't want space in typed word as well.
$("#org").on("keydown", function(e){
if(e.keyCode == 32){
my_func();
return false;//to fix the scrolling down on space bar key press
}
});