I have a search box which is by default not autofocused.
So i am putting a keypress event on the body i.e. when forward slash (/) is pressed the search box should be in focus. Although on key press it puts the search box in focus but also puts the "/" in the search box.
body.onkeypress = (e) => {
if(e.which === 47) {
searchInput.focus()
}
}
How should I fix this?
Use preventdefault to prevent the '/' from being typed.
Make sure you do this in your if statement, otherwise all characters get blocked.
body.onkeypress = (e) => {
if(e.which === 47) {
e.preventDefault()
searchInput.focus()
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
<body id="body">
<input type="text" id="elementid" />
</body>
<script>
document.onkeypress = (e) => {
if (e.which === 47) {
document.getElementById("elementid").focus();
setTimeout(() => {
str = document.getElementById("elementid").value = document
.getElementById("elementid")
.value.slice(0, -1);
});
}
};
</script>
Before you read furtherly, look at my answer and Priyal Pithadiya answer for two different methods on how you can do this.
I have a client that is not satisfied with the solution I got from yesterdays answer on here. Basically I have this script that prevents non number characters from being inserted in an input. It works perfectly when you type but I have a problem here I cannot figure out how to prevent non numbers from being pasted in.
My client has stated that he want to avoid using input number since that was the solution that was offered here but for personal reasons he said he needs to use input text.
If I have to change my code to get a result like this I will.
Please note, I cannot use jQuery, my solution must be javascript only.
This is my code:
//Prevent non numbers from keypress
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
//Prevent non numbers from being pasted only numbers can be pasted
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(){
//???
}
<input type="text" id='numbers-only'>
# try with given solution ,
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(event){
window.setTimeout(() => {
var characters =event.target.value;
window.setTimeout(() => {
if(!(/^\d+$/.test(characters))){
event.target.value = event.target.value.replace(/\D/g, '');
}
});
});
}
<input type="text" id="numbers-only" >
in-line js:
<input type="text" pattern="\d{1,}" onkeyup="this.value = this.value.replace(/[^0-9]/g, '')" />
You can use onpaste Event if you want.
<input type="text" id='numbers-only' onchange="removeChars()">
function removeChars() {
var input = document.getElementById('numbers-only');
input.value = input.value.replace(/[^0-9]/g, '');
}
Thanks Priyal Pithadiya for your help I will like to post two versions of Priyal Pithadiya examples from earlier and now which includes two versions one is with
a onpaste example and the other one is based on using an addEventListener by paste this is for any future readers reading this. All credit goes to Priyal Pithadiya.
With onpaste
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
function myFunction(e) {
var el = e;
setTimeout(function() {
el.value = el.value.replace(/\D/g, '');
}, 0);
}
<input type="text" id="numbers-only" onpaste="myFunction(this);" >
With a event listener
document.querySelector('#numbers-only').addEventListener('keypress',preventNonNumbersInInput);
function preventNonNumbersInInput(event){
var characters = String.fromCharCode(event.which);
if(!(/[0-9]/.test(characters))){
event.preventDefault();
}
}
document.querySelector('#numbers-only').addEventListener('paste',pasteTest);
function pasteTest(event){
window.setTimeout(() => {
var characters =event.target.value;
window.setTimeout(() => {
if(!(/^\d+$/.test(characters))){
event.target.value = event.target.value.replace(/\D/g, '');
}
});
});
}
<input type="text" id="numbers-only" >
<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
$('.dot').keydown(function(){
$(this).val($(this).val().toString().replace(/\./g, ','));
})
http://jsfiddle.net/ZtkBW/
In this example i replace dot to comma. How can i block the addition of two commas in current input?
If in input is already one comma then next should be remove.
This is a classic case of trying to solving a problem with regular expressions, and now you have two problems...
It's not clear exactly what you want, but this will stop multiple presses of the comma key. It should be a short step from here to detect the period (code 190) and do whatever you want with it instead.
$('.dot').keydown(function(e){
if (e.which == 188) {
if (this.value.indexOf(',') != -1) {
e.preventDefault();
return false;
}
}
});
Use the keypress event instead of the keydown event (as keydown isn't triggered by key repeat).
Look for the . and , characters, and stop the event by returning false if there already is a comma in the text.
As the event is stoppable, it occurs before the value is changed, so you need to use a timeout for replacing the period with a comma.
$('.dot').keypress(function(e){
var txt = $(this).val();
if (e.which == 46) {
if (txt.indexOf(',') != -1) {
return false;
} else {
var t = $(this);
window.setTimeout(function(){
t.val(t.val().replace('.', ','));
}, 0);
}
} else if (e.which == 44) {
return txt.indexOf(',') == -1;
}
});
Demo: http://jsfiddle.net/eAkUc/1/
$('.dot').keypress(function(e){
if( ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) &&
(e.charCode==','.charCodeAt(0) || e.charCode=='.'.charCodeAt(0)) )
e.preventDefault();
else
$(this).val($(this).val().toString().replace(/\./g, ','));
});
DEMO
If I understand what you want correctly, here's one way of doing it:
var myVal = $(this).val();
myVal[myVal.indexOf(",")] = ".";
myVal.split(",").join("");
$(this).val(myVal);
I have placed one textbox.... I want to put restriction on it ..
that digits and special characters should not be allowed to input in textbox...
how can i do using onkeypress event in Javascript ???
my code is ...
<script>
function event()
{
document.getElementById("TX1").addEventListener("keypress", handleKeyPress, false);
}
function handleKeyPress(e)
{
var restricted = "0123456789_#!";
var key = e.keyCode || e.which;
var i=0;
for(;i<restricted.length;i++)
{
if (restricted.charCodeAt(i) == key)
{
e.returnValue = false;
}
return true;
}
</script>
<body onLoad="event();">
<input type="text" name="T1" id="TX1" size="27" maxlength="35" >
</body>
that digits and special characters should not be allowed to input in textbox...
Don't do this through keypress filtering. It's user-hostile, confusing, messes up other control keypresses and is easy to defeat by using other methods of input, such as copy/paste, drag/drop, form fillers, spellcheckers, IMEs...
Instead, have a warning that visibly directs the user when they've put something unexpected in, eg.:
<input type="text" name="T1" id="TX1"/>
<div id="TX1_help">
Please do not use numbers or ‘!’, ‘_’ or ‘#’ characters in this field.
</div>
<script type="text/javascript">
var tx1= document.getElementById('TX1');
var tx1help= document.getElementById('TX1_help');
function checkTX1() {
var isok= /^[^0-9_#!]*$/.test(tx1.value);
tx1help.style.display= isok? 'none' : 'block';
}
checkTX1();
// Re-check the field every time a key is pressed or other change event.
// To ensure it is still checked in a timely fashion in the case of
// non-keyboard events, add a timer as well.
//
tx1.onchange=tx1.onkeyup= checkTX1;
setInterval(checkTX1, 500);
</script>
You can use addEventListener for the event attachment if you want to, but be aware this won't work in IE<9, for which you would need the attachEvent model. (event.returnValue is specific to the IE attachEvent model and will not work with addEventListener, which uses event.preventDefault() instead.)
Try the following:
document.getElementById('TX1').addEventListener('keypress', function(event) {
if (event.keyCode == 13) {
handleKeyPress();
}
});
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