I've been learning some jQuery and using w3schools. My intention is to allow the user to bind any key on their keyboard to the currently hardcoded key. I tried creating a variable and having that changed based on the input of the text field to change the keycode but haven't had any luck (Just like how you see in some games when they allow you to map a key to another). I was researching on w3schools and I believe I could use switch case, but I believe that would be too long and not tidy?
Here is what I have so far. (Alert doesn't seem to work here, going to the actual JSFiddle via the hyperlink works though)
$('input').bind("binding", function(e) {
alert("Backspace"); //Pop up to see
});
$('input').keyup(function(e) {
if (e.keyCode == 8) { // 8 = backspace
$(this).trigger("binding"); //will allow the message to be displayed
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try it here <input type="text"> Change the input <input class type="text">
Any suggestions are grateful. Thank you
You can try this for binding one key to backspace. It takes input from the first input element and the key pressed is then bounded to the backspace and only that key will function as a backspace key
$('#try').bind("binding", function(e) {
alert("Backspace"); //Pop up to see
});
var a;
$('#change').keyup(function(e) {
a = e.keyCode;
$(this).prop('disabled', true);
});
$('#try').keyup(function(e) {
if (e.keyCode == a) {
$(this).trigger("binding"); //will allow the message to be displayed
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Press the key you want to bind to backspace <input type="text" id="change"><br> Change the input <input id="try" type="text">
By default the binded key will be Backspace. You can change the key by typing something in the first input. It will take only one character.
Then when that key is input in the second input field the message will be triggered.
Explanation:
The keycode of the key entered in the first input is saved in the key_code variable and used later on in the other key_up event to check whether it matches
var key_code = 8
$('#changekey').keyup("input", function(e) {
key_code = e.keyCode;
});
$('input').on("binding", function(e) {
alert("Backspace"); //Pop up to see
});
$('#text').keyup(function(e) {
if (e.keyCode == key_code) //8 = backspace
{
$(this).trigger("binding"); //will allow the message to be displayed
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try it here <input type="text" id="changekey" maxlength = 1 > Change the input <input class type="text" id="text">
I have written the below code so that users only enter numbers. It works fine in all the browsers excepts FireFox
In FireFox after entering a number if the users clicks backspace it is not working properly. Below is the code.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function getKeyCodeFromEvent(e) {
if (typeof e == "object" && typeof e.which == "number") {
return e.which;
}
return window.event.keyCode;
}
function checkEntry(e) {
var keyCode = this.getKeyCodeFromEvent(e);
var regularExpression = /^[0-9.]+$/;
return regularExpression.test(String.fromCharCode(keyCode));
}
</script>
</head>
<body>
<input type="text" onkeypress="return checkEntry(event);" />
</body>
</html>
When someone presses the backspace key, you get the value 8 from getKeyCodeFromEvent. Running it in String.fromCharCode(8); then returns the following unicode value: ``. This does not match your regex, so it fails.
You could solve this by checking that the backspace, delete, tab, left and right keys are allowed, before turning them into String values. You will need to use the keydown event though, because keypress does not return values for certain keys, such as left or right.
Be careful when restricting user movement like this though, as it might easily make people angry, when the site doesn't work as they expect it to.
<script>
function getKeyCodeFromEvent(e) {
if (typeof e == "object" && typeof e.which == "number") {
return e.which;
}
return window.event.keyCode;
}
function checkEntry(e) {
var keyCode = getKeyCodeFromEvent(e);
var regularExpression = /^[0-9.]+$/;
// If the key is backspace, tab, left, right or delete
if([8,9,37,39,46].indexOf(keyCode) !== -1 || e.ctrlKey || e.metaKey) {
return true;
}
if(!regularExpression.test(String.fromCharCode(keyCode))) {
e.preventDefault();
e.returnValue = false;
return false;
}
}
// I took the liberty of moving your event from the HTML into JavaScript, where it belongs
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('numberinput').addEventListener("keydown", checkEntry, false);
}, false);
</script>
<input type="text" id="numberinput" />
http://jsfiddle.net/8hzwLjfz/6/
Hi I'm practicing JS and I have a question from javascript.
I'm gonna make the user to type only letters and if the user decides to type numbers too, the program stop him/her. and please no jQuery Answers cuz I don't know anything about it yet.
here's my code......
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function vent (t)
{
var m=/^[a-zA-Z]+$/
t=document.getElementById("txt");
if(t.value.match(m))
{
alert("Co");
return true;
}
else
{
// I want to write my preventing code here.......
}
}
</script>
</head>
<body>
<input type="text" id="txt" onBlur="vent (this)"/><br/>
<input type="text"/>
</body>
</html>
When restricting user input to a subset of key values you would typically use the onkeydown event rather than blur. That way you can prevent the user's keystroke from being added to the input value rather than trying to remove it after the fact. All you need to do is cancel the event, using preventDefault() or returning false from the keydown handler. Note for older browsers you may need to check for keyCode in addition to which, i.e., var c = e.which || e.keyCode; then check the value of c against the allowed range.
function allowOnlyCharacters(e)
{
return e.which == 16 || (e.which >= 65 && e.which <= 90);
}
var element = document.getElementById('txt');
element.onkeydown = allowOnlyCharacters;
<input type="text" id="txt"/><br/>
<input type="text"/>
I have a web application where on one specific screen I have to make sure the user clicked the button using the mouse as opposed to just pressing enter or space.
I have written this code:
$('button').keydown(function (e) {
if (e.which === 10 || e.which === 13 || e.which === 32) {
return false;
}
});
However, this only works for enter. The form can still be submitted by pressing space on a button. I am just wondering what caused this inconsistency and how to get around it?
Edit:
Example fiddle: http://jsfiddle.net/billccn/3JmtY/1/. Check the second check box and pressing enter while the focus is on the button will have no effect. If I further disable the input and expand the keydown trapping to the whole form, then enter cannot be used to submit the form.
Edit 2:
I do have a backup plan which is replacing the button with a link or even a plain div and use the click event to submit the form programmatically. However, extra work is required to make it look like a button so I'd rather use a button is possible.
Just found out: handling space (32) on keyup will prevent the click event.
Updated fiddle: http://jsfiddle.net/3JmtY/2/
Missed the Point of your Question. After some googleing if found the following trick:
Bind the keypress event to your from and listen to it's keycode. If the keycode is 13
(enter), prevent all default actions (event.preventDefaul()) and prevent further event bubbeling ( return false; ).
Her is a fiddler code example:
HTML:
<form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">Trigger the handler</div>
JavaScript:
$('#target').keypress(function (event) {
var code = event.keyCode || event.which;
if (code == 13) {
event.preventDefault();
return false;
}
});
$('#target').submit(function (event, data2) {
debugger;
alert('test');
return false;
});
Fiddler: http://jsfiddle.net/ggTDs/
Note that the form is not submited when enter is clicked!
Use below code. 13 for Enter key and 32 for Spacebar.
$("#form_id").on('keydown keyup keypress', function( e ) {
if ( e.keyCode == 13 || e.which == 13 || e.which == 32 ) {
e.preventDefault();
return false;
}
});
I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call my JavaScript function, but when I press it, the form is submitted.
How do I prevent the form from being submitted when the enter key is pressed?
if(characterCode == 13) {
// returning false will prevent the event from bubbling up.
return false;
} else{
return true;
}
Ok, so imagine you have the following textbox in a form:
<input id="scriptBox" type="text" onkeypress="return runScript(event)" />
In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.
function runScript(e) {
//See notes about 'which' and 'key'
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.
NOTE:
It's been pointed out that keyCode is now deprecated. The next best alternative which has also been deprecated.
Unfortunately the favored standard key, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.
Furthermore, while the deprecated warning is quite ominous about keyCode and which, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.
Use both event.which and event.keyCode:
function (event) {
if (event.which == 13 || event.keyCode == 13) {
//code to execute here
return false;
}
return true;
};
event.key === "Enter"
More recent and much cleaner: use event.key. No more arbitrary number codes!
NOTE: The old properties (.keyCode and .which) are Deprecated.
const node = document.getElementsByClassName("mySelect")[0];
node.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
// Do more work
}
});
Modern style, with lambda and destructuring
node.addEventListener("keydown", ({key}) => {
if (key === "Enter") // Handle press
})
Mozilla Docs
Supported Browsers
If you're using jQuery:
$('input[type=text]').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
Detect Enter key pressed on whole document:
$(document).keypress(function (e) {
if (e.which == 13) {
alert('enter key is pressed');
}
});
http://jsfiddle.net/umerqureshi/dcjsa08n/3/
Override the onsubmit action of the form to be a call to your function and add return false after it, ie:
<form onsubmit="javascript:myfunc();return false;" >
A react js solution
handleChange: function(e) {
if (e.key == 'Enter') {
console.log('test');
}
<div>
<Input type="text"
ref = "input"
placeholder="hiya"
onKeyPress={this.handleChange}
/>
</div>
So maybe the best solution to cover as many browsers as possible and be future proof would be
if (event.which === 13 || event.keyCode === 13 || event.key === "Enter")
Here is how you can do it using JavaScript:
//in your **popup.js** file just use this function
var input = document.getElementById("textSearch");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
alert("yes it works,I'm happy ");
}
});
<!--Let's say this is your html file-->
<!DOCTYPE html>
<html>
<body style="width: 500px">
<input placeholder="Enter the text and press enter" type="text" id="textSearch"/>
<script type="text/javascript" src="public/js/popup.js"></script>
</body>
</html>
Below code will add listener for ENTER key on entire page.
This can be very useful in screens with single Action button eg Login, Register, Submit etc.
<head>
<!--Import jQuery IMPORTANT -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<!--Listen to Enter key event-->
<script type="text/javascript">
$(document).keypress(function (e) {
if (e.which == 13 || event.keyCode == 13) {
alert('enter key is pressed');
}
});
</script>
</head>
Tested on all browsers.
A jQuery solution.
I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.
$(selector).keyup(function(e){
/*
* Delay the enter key form submit till after the hidden
* input is updated.
*/
// No need to do anything if it's not the enter key
// Also only e.which is needed as this is the jQuery event object.
if (e.which !== 13) {
return;
}
// Prevent form submit
e.preventDefault();
// Trigger the blur event.
this.blur();
// Submit the form.
$(e.target).closest('form').submit();
});
Would be nice to get a more general version that fired all the delayed events rather than just the form submit.
A much simpler and effective way from my perspective should be :
function onPress_ENTER()
{
var keyPressed = event.keyCode || event.which;
//if ENTER is pressed
if(keyPressed==13)
{
alert('enter pressed');
keyPressed=null;
}
else
{
return false;
}
}
A little simple
Don't send the form on keypress "Enter":
<form id="form_cdb" onsubmit="return false">
Execute the function on keypress "Enter":
<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">
Using TypeScript, and avoid multiples calls on the function
let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;
function SearchListEnter(event: KeyboardEvent) {
if (event.which !== 13) {
return;
}
// more stuff
}
<div class="nav-search" id="nav-search">
<form class="form-search">
<span class="input-icon">
<input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
<i class="ace-icon fa fa-search nav-search-icon"></i>
</span>
<input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
</form>
</div>
<script type="text/javascript">
$("#search_value").on('keydown', function(e) {
if (e.which == 13) {
$("#search").trigger('click');
return false;
}
});
$("#search").on('click',function(){
alert('You press enter');
});
</script>
native js (fetch api)
document.onload = (() => {
alert('ok');
let keyListener = document.querySelector('#searchUser');
//
keyListener.addEventListener('keypress', (e) => {
if(e.keyCode === 13){
let username = e.target.value;
console.log(`username = ${username}`);
fetch(`https://api.github.com/users/${username}`,{
data: {
client_id: 'xxx',
client_secret: 'xxx'
}
})
.then((user)=>{
console.log(`user = ${user}`);
});
fetch(`https://api.github.com/users/${username}/repos`,{
data: {
client_id: 'xxx',
client_secret: 'xxx'
}
})
.then((repos)=>{
console.log(`repos = ${repos}`);
for (let i = 0; i < repos.length; i++) {
console.log(`repos ${i} = ${repos[i]}`);
}
});
}else{
console.log(`e.keyCode = ${e.keyCode}`);
}
});
})();
<input _ngcontent-inf-0="" class="form-control" id="searchUser" placeholder="Github username..." type="text">
<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">
Add this Code In Your HTML Page...it will disable ...Enter Button..
Cross Browser Solution
Some older browsers implemented keydown events in a non-standard way.
KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.
which
and keyCode are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.
The isKeyPressed function checks if the pressed key was enter and event.preventDefault() hinders the form from submitting.
if (isKeyPressed(event, 'Enter', 13)) {
event.preventDefault();
console.log('enter was pressed and is prevented');
}
Minimal working example
JS
function isKeyPressed(event, expectedKey, expectedCode) {
const code = event.which || event.keyCode;
if (expectedKey === event.key || code === expectedCode) {
return true;
}
return false;
}
document.getElementById('myInput').addEventListener('keydown', function(event) {
if (isKeyPressed(event, 'Enter', 13)) {
event.preventDefault();
console.log('enter was pressed and is prevented');
}
});
HTML
<form>
<input id="myInput">
</form>
https://jsfiddle.net/tobiobeck/z13dh5r2/
Use event.preventDefault() inside user defined function
<form onsubmit="userFunction(event)"> ...
function userFunction(ev)
{
if(!event.target.send.checked)
{
console.log('form NOT submit on "Enter" key')
ev.preventDefault();
}
}
Open chrome console> network tab to see
<form onsubmit="userFunction(event)" action="/test.txt">
<input placeholder="type and press Enter" /><br>
<input type="checkbox" name="send" /> submit on enter
</form>
I used document on, which covers dynamically added html after page load:
$(document).on('keydown', '.selector', function (event) {
if (event.which == 13 || event.keyCode == 13) {
//do your thang
}
});
Added updates from #Bradley4