I am having problem with the following code. It is a simple To Do app with Javascript. Following a tutorial, followed to the t. My app isn't working the way it is supposed to. When I press the enter key the input value should be added to the list and it is not. I can't find any flaw in the code.
Also when I call the function manually addToDo("read"); it shows up alright. But the enter button is not responding. Any advice will be appreciated.
document.addEventListener("keyup", function(event) {
if (event.key === 13) {
const toDo = input.value;
if (toDo) {
addToDo(toDo);
} //end if toDo
} // end if event.key
});
It doesn't work because you're not checking for the proper key value on the keyup event:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
You can check for the 'Enter' key on the keyup event like so:
txtTodo.addEventListener('keyup', (e) => {
if (e.key === 'Enter') {
console.log(e.target.value);
}
});
A live example can be found here:
https://jsfiddle.net/dbkf53w2/
function addToDo(val) {
console.log(val);
}
document
.querySelector('#input-field')
.addEventListener('keyup', function (event) {
if (event.key === 'Enter') {
const toDo = event.target.value;
if (toDo) {
addToDo(toDo);
} //end if toDo
} // end if event.key
});
<input type="text" id="input-field">
event.key value has a string value. Try with 'Enter' rather than 13. Number is keyCode. When trying to console event.keyCode then it shows numbers.
document.addEventListener("keyup", function(event){
console.log(event.keyCode);
if(event.key=== 'Enter'){
//const toDo = input.value;
//if(toDo){
// addToDo(toDo);
console.log('Enter')
//}//end if toDo
}// end if event.key
})
<div>Push 'Enter' please</div>
Related
I have the following code:
undoButton.onclick = undoFunction;
document.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") {
e.preventDefault();
undoFunction();
}
});
function undoFunction() {
console.log("undo function...");
}
When I click the button, as excepted, the function code runs once, and so does the console.log, but when I use the key stroke, the function is running a multiple times, up to hundreds of so-called loops at some scenarios. Any suggestion why? I tried to used e.repeat = false but had no luck. Thanks!
Use keyup instead. The keydown event triggers as long a key is hold down. keyup only triggers when a key is released.
var undoButton = document.getElementById('undoButton');
undoButton.onclick = undoFunction;
document.addEventListener("keyup", (e) => {
if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") {
e.preventDefault();
undoFunction();
}
});
function undoFunction() {
console.log("undo function...");
}
<input id="undoButton" type="button" value="Undo" />
I have a input for searchbox. I must make like; Write my words fors search then after i press enter it must need go another page with input value. So i can access that value with query string. So how can i route another page with value of input after i press enter ? Thank you for help! I Just add That codes for catch enter press.
useEffect(() => {
const listener = (event) => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
alert("Enter key was pressed. Run your function.");
event.preventDefault();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
You don't necessarily have to set an event listener, using onKeyDown event handler will also do. Enter key has a code of 13, so we just have to detect that.
Keep your value in a state (here, myValue), detect that you've pressed Enter key (here, using keyPressHandler method), and finally, pass the parameter to your route.
import {useHistory} from "react-router-dom"
function App() {
let history = useHistory();
const [myValue, setMyValue] = useState("");
const handleChange = ({ target: { value } }) => {
setMyValue(value);
};
const keyPressHandler = (e) => {
if (e.which === 13) {
// alert("You pressed enter!");
history.push("/process/" + myValue);
}
};
return (
<div className="App">
<input value={myValue} onKeyDown={keyPressHandler} onChange={handleChange} />
</div>
);
}
UPDATE:
According to MDN Web Docs, e.which is non-standard [Source] and e.keyCode is deprecated [Source], so you should be using e.key instead like:
const keyPressHandler = (e) => {
if (e.key=== 'Enter') {
// alert("You pressed enter!");
history.push("/process/" + myValue);
}
};
Working CodeSandbox Link
In below code if I press 'a' after some keys it should remove everything from input including but 'a' is not going away in below code.
const input = document.querySelector("input");
function type(e) {
if (e.key === "a") {
console.log("helo");
input.value = "";
}
}
window.addEventListener("keydown", type);
The problem that you are having is that the keydown event fires before the character is added to the input. To resolve this, you must use the keyup event.
var input = document.getElementById("exampleInput");
function type(e) {
if (e.key === "a") {
console.log("helo");
input.value = "";
}
}
window.addEventListener("keyup", type);
<input type="text" id="exampleInput" />
The handler fires before the default action of the keydown fires. This is why you can use event.preventDefault() on key events - the handlers fire before the default action occurs, which is why the default actions are cancelable with preventDefault().
So, for what you're trying to do, clear the value and call preventDefault():
const input = document.querySelector('input');
window.addEventListener("keydown", type);
function type(e) {
if (e.key === "a") {
console.log("clearing");
input.value = "";
e.preventDefault();
}
}
<input>
how to disable the "enter" key who give us the possibility to valid and send the form if the field is not valid ?
I only did the first part, which indicates that the field is not valid, but the "enter" key is always active . So my question is simple, how to disable the "enter" key button from the moment we see the "error-message" under the field
here is my test page ->
http://500milligrammes.com/facticemagazine/final/unsubscribe/
I've checked your website, to achieve what you asked for:
$("#name").on("keydown", function(e) {
if(e.which === 13 && $("#name").next(".error-message").is(":visible")) {
e.preventDefault();
return false;
}
});
The submit is always send on keydown, so we need to add a keydown event handler.
Next is to check if the key was the enter key e.which === 13 and after that we just need to check if the error message is shown or not $("#name").next(".error-message").is(":visible").
If both conditions are true then just prevent the default action (submit) by calling e.preventDefault();
You can further improve this by also checking if the input is empty or not before accepting the enter key. The first keydown might be the enter key.
$("#name").on("keydown", function(e) {
if(e.which === 13) {
if($("#name").next(".error-message").is(":visible") || !$("#name").val()) {
e.preventDefault();
return false;
}
}
});
You can check it using the keycode value (13) of enter key.
Something like the following should do:
$('form').on('keyup keypress', function(e) {
if (e.which == 13) {
if (!isValid()) { // your validation function
e.preventDefault();
return false;
} else {
$(this).submit();
}
}
});
Try adding this when you show the error:
$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
if(e.which == 13) {
e.preventDefault();
return false;`enter code here`
}
});
I'm trying to do a function if enter is pressed while on specific input.
What I'm I doing wrong?
$(document).keyup(function (e) {
if ($(".input1").is(":focus") && (e.keyCode == 13)) {
// Do something
}
});
Is there a better way of doing this which would say, if enter pressed on .input1 do function?
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
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("input1")[0];
node.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// Do work
}
});
Modern style, with lambda and destructuring
node.addEventListener("keyup", ({key}) => {
if (key === "Enter") {
// Do work
}
})
If you must use jQuery:
$(document).keyup(function(event) {
if ($(".input1").is(":focus") && event.key == "Enter") {
// Do work
}
});
Mozilla Docs
Supported Browsers
$(document).keyup(function (e) {
if ($(".input1:focus") && (e.keyCode === 13)) {
alert('ya!')
}
});
Or just bind to the input itself
$('.input1').keyup(function (e) {
if (e.keyCode === 13) {
alert('ya!')
}
});
To figure out which keyCode you need, use the website http://keycode.info
Try this to detect the Enter key pressed in a textbox.
$(function(){
$(".input1").keyup(function (e) {
if (e.which == 13) {
// Enter key pressed
}
});
});
The best way I found is using keydown ( the keyup doesn't work well for me).
Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)
$('input').keydown( function( event ) {
if ( event.which === 13 ) {
// Do something
// Disable sending the related form
event.preventDefault();
return false;
}
});
It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
The solution that work for me is the following
$("#element").addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// do something
}
});
Try this to detect the Enter key pressed in a textbox.
$(document).on("keypress", "input", function(e){
if(e.which == 13){
alert("Enter key pressed");
}
});
DEMO
A solution that worked for me is this:
<input onkeydown="if (event.key == 'Enter'){//do logic}else{}">
$(document).ready(function () {
$(".input1").keyup(function (e) {
if (e.keyCode == 13) {
// Do something
}
});
});
This code handled every input for me in the whole site. It checks for the ENTER KEY inside an INPUT field and doesn't stop on TEXTAREA or other places.
$(document).on("keydown", "input", function(e){
if(e.which == 13){
event.preventDefault();
return false;
}
});
Here is what I did for my angular project:
HTML:
<input
class="form-control"
[(ngModel)]="searchFirstName"
(keyup)="keyUpEnter($event)"
/>
TypeScript:
keyUpEnter(event: KeyboardEvent) {
if (event.key == 'Enter') {
console.log(event);
}
}