JavaScript Input Focus Switching - javascript

I have the below code being used in a new web app of mine, though I can't seem to get it to work like it should.. I want to be able to load up the page, then if the client hits the "Tab" key then it will simply just focus to the other input field. There being only 2 input fields, this should be easy (at least I thought :P). Anyways, can anybody help me with this? Thanks in advance :)
var body = document.querySelector('body');
body.onkeydown = function (e) {
if ( !e.metaKey ) {
// e.preventDefault();
}
if (e.code == "Tab") {
console.log(e.code);
if ($('#username').is(":focus")) {
$('#password').focus();
} else if ($('#password').is(":focus")) {
$('#username').focus();
}
}
}

I'm assuming you're using JQuery since you use $ in your javascript so I wrote this example under that assumption. I'm assuming you want it to tab into the field regardless so if they press the tabkey, it defaults to the id="username" input element. I added in a preventDefault to stop the normal tab behavior. It seems that the tabs normal behavior is what causes it to not function properly. Hope I didn't misunderstand you and that this helps.
$("body").on("keydown", function(e) {
if (e.which !== 9 && e.keyCode !== 9) {
return;
}
console.log("Which Value:", e.which);
console.log("KeyCode Value:", e.keyCode)
e.preventDefault();
if (!$('#username').is(":focus")) {
$('#username').focus();
} else {
$('#password').focus();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="username">
<input id="password">
</body>
EDIT:
In case you wanted to do this without the JQuery selectors. Here's another example:
var body = document.getElementsByTagName("body");
body[0].onkeydown = function(e) {
var username = document.getElementById("username");
var password = document.getElementById("password");
if (e.which !== 9 && e.keyCode !== 9 && e.code !== "Tab") {
return;
}
e.preventDefault();
if (document.activeElement !== username) {
username.focus();
} else {
password.focus();
}
}
<body>
<input id="username">
<input id="password">
</body>

Simply, use autofocus to make default focus to UserID and use tabindex to move to password when user press Tab key.
UserId :<input type="text" name="fname" autofocus tabindex="1">
Password: <input type="text" name="fname2" tabindex="2">

You need e.PreventDefault() to stop the tab event from propagating and doing what it was going to do anyway. Only ignore event propagation for the tab key.
body.onkeydown = function (e) {
if (e.code == "Tab") {
console.log(e.code);
if ($('#username').is(":focus")) {
$('#password').focus();
} else if ($('#password').is(":focus")) {
$('#username').focus();
}
e.preventDefault();
}
}
Also consider setting type="password" on your password input.

Related

How to disable enter on input only in some parts?

I am currently running this as I don't want users to press enter on their keyboard to launch an input and it works.
jQuery(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
However I have one part of the site where this shouldn't be avoided and i tried the following but it didn't work
if(jQuery(".tab-pane").is("#step6")) {
jQuery(window).keydown(function(e){
if(e.keyCode == 13) {
return true;
}
});
}
I guess the first overrides the second
Yes..first function is replace the second one.so use like this .Include the second function inside the first .Events are same, condition only different
jQuery(window).keydown(function(event){
if(event.keyCode == 13) {
if(jQuery(".tab-pane").is("#step6")) {
return true;
}
else{
event.preventDefault();
return false;
}
}
});
You may need to slightly tweek the code & check this condition inside keydown
jQuery(window).keydown(function(event) {
// checking current keycode
if (13 == event.keyCode) {
// the is condition
if (jQuery(".tab-pane").is("#step6")) {
return !0; // will return true
}
event.preventDefault(); // otherwise will prevent default behaviour
return !1 // will return false
}
});
I suggest attaching the event of the click to each input not to the window :
<input type="text" onkeypress="myFunction(event)">
myFunction() should be like this :
function myFunction(e) {
if (e.keyCode == 13) {
//do whatever you want
}
}
Hope this was useful
Try using classes to make it easy.. just add the class prevent-enter on the inputs you want to avoid the keypress.
$(document).ready(function() {
$('.prevent-enter').keydown(function(e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get" action="javascript:alert('form submitted');">
<input class="prevent-enter" placeholder="This prevents enter keypress" /><br>
<input class="" placeholder="This accepts enter keypress" /><br>
<input type="submit" />
</form>

Event Binding on Dynamically Created Element

I have just begun my exploration of javascript and jquery, and would sincerely appreciate any help with my current dilemma. The feature that I am trying to build involves a number of steps:
The 'enter' key triggers an event.
The appropriate value ('About', 'Contact', or 'Extra') within the input field will open a new page.
The input field (residing within a <p> element) is then cloned and inserted, allowing the user to input another value.
My dilemma involves binding. Once the input field has been cloned, the page that was first opened will continue to open regardless of a new input value. Meaning, if the 'About' page was first opened, then the 'About' page will continue to open even when a new value ('Contact' or 'Extra') is added to the inserted input field. Here is the code that I have written:
javascript
$(function() {
function cloneInput() {
var clonedElement = $("p").last().clone(true);
$("input").last().prop("disabled", true);
clonedElement.insertAfter($("p").last()).prop("id", "seven");
$("input").last().prop("value", "").focus();
}
$("#input-text").keydown(function(event) {
var keypressed = event.keyCode || event.which;
var text = $("#input-text").val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
});
html
<!DOCTYPE html>
<html>
<head>
<link href="css/stylesheet.css" type="text/css" rel="stylesheet"/>
<script src="js/jquery-3.1.0.js"></script>
<script src="js/scripts.js"></script>
</head>
<body id="index-body">
<p id="one">Hello friend. My name is $%^&*$^%. Welcome to ##$%%%*&.</p>
<p id="two">To learn more, please enter a command:</p>
<p id="three">> About</p>
<p id="four">> Contact</p>
<p id="five">> Extra</p>
<p id="six">> %<input type="text" maxlength="40" autofocus id="input-text"></p>
</body>
</html>
result
<p id="six">
<input type="text" maxlength="40" autofocus id="input-text" disabled>
</p>
<p id="seven">
<input type="text" maxlength="40" autofocus id="input-text">
</p>
I have searched stackoverflow and learned about .on(), .off(), and .change(). In addition, I have utilized these methods when refactoring my code. Still, I cannot find a solution. Thank you in advance.
Note: I am aware that my naming conventions need to be cleaned up.
bind your event on document itself not on the element you want to trigger
$(document).on('keydown', "#input-text", function(event) {
e.preventDefault();
// all your code..
});
see my other answer.
If you want to call a function on dynamically created elements, you should use
$(document).on(<event>, <object>, function(event) {
});
Example : This will perform the action on clicking the elements with class class1 ( even on dynamically created elements )
$(document).on('click', '.class1', function(event) {
/* do something here */
});
In your case :
$(document).on("click", "#input-text", function(event) {
var keypressed = event.keyCode || event.which;
var text = $("#input-text").val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
Everything is looking good only one issue is accessing filed value instead of $('#input-text').val() use $(this).val() always gets current element value..
$(function() {
function cloneInput() {
var clonedElement = $("p").last().clone(true);
$("input").last().prop("disabled", true);
clonedElement.insertAfter($("p").last()).prop("id", "seven");
$("input").last().prop("value", "").focus();
}
$("#input-text").keydown(function(event) {
var keypressed = event.keyCode || event.which;
var text = $(this).val();
if (keypressed == 13) {
if (text == "About") {
window.open("about.html", "_blank");
cloneInput();
} else if (text == "Contact") {
window.open("contact.html", "_blank");
cloneInput();
} else if (text == "Extra") {
window.open("extra.html", "_blank");
cloneInput();
} else {
$("<p>Command not found</p>").insertAfter("#six").prop("id", "error");
}
}
});
});

Default button on enter and popup list

I'm trying to implement a form with multiple buttons on it. When I press enter I want to have my default button submitted. This code from http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/ generally works:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
});
but...
when I type in input field I have an autocomplete popup so when I press enter in this popup I expect to put this value to input field, not submit all form. Can I check somehow if this enter comes from popup? Or I should try to do this different way?
EDIT:
I think I didn't say it clear. This popup is not any part of jquery. It's standard popup that shows previously typed data into input. So it hasn't got any class nor id. Stop propagation doesn't work either. None of solutions below resolve this problem
You could use :visible to see if the dropdown div for the autocomplete is open, and then prevent the enter key action of your code completing. Something like this:
$("form input").keypress(function(e) {
var key = e.which || e.keyCode;
if (key == 13 && !$(".autocomplete").is(":visible")) {
e.preventDefault();
$('form').submit();
}
});
You could also use event.stopPropagation() on the enter key press in the autocomplete function, however you'll probably have to amend the source manually which isn't ideal.
Before return false;
write
e.preventDefault();
or/and
e.stopPropagation();
$("form input").keypress(function (e) {
if (e.target.id !== "autoCompliteId" && ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
I modified my code and it works now.
I have an enum called Operation in my command and I set different value of the field before every submit button eg:
<input type="submit" value="do sth" onclick="setOperationAndSubmit('DO_STH')"/>
<input type="submit" value="next" onclick="setOperationAndSubmit('DEFAULT')"/>
function setOperationAndSubmit(operation) {
if (document.myForm.elements['operation'].value === '') {
document.myForm.elements['operation'].value = operation;
}
document.myForm.submit();
}
Then I have my action that listens to keypress and it set appropriate operation on every enter key:
$(function() {
$("form input").keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
document.myForm.elements['operation'].value = 'DEFAULT';
}
});
});
so default action is executed when I press enter

Prevent form submission on Enter key press

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

Trigger a button click with JavaScript on the Enter key in a text box

I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box?
There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
In jQuery, the following would work:
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode === 13) {
$("#id_of_button").click();
}
});
$("#pw").keyup(function(event) {
if (event.keyCode === 13) {
$("#myButton").click();
}
});
$("#myButton").click(function() {
alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton">Submit</button>
Or in plain JavaScript, the following would work:
document.getElementById("id_of_textbox")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("id_of_button").click();
}
});
document.getElementById("pw")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function buttonCode()
{
alert("Button code executed.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button>
Then just code it in!
<input type = "text"
id = "txtSearch"
onkeydown = "if (event.keyCode == 13)
document.getElementById('btnSearch').click()"
/>
<input type = "button"
id = "btnSearch"
value = "Search"
onclick = "doSomething();"
/>
Figured this out:
<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />
<script>
function searchKeyPress(e)
{
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13)
{
document.getElementById('btnSearch').click();
return false;
}
return true;
}
</script>
Make the button a submit element, so it'll be automatic.
<input type = "submit"
id = "btnSearch"
value = "Search"
onclick = "return doSomething();"
/>
Note that you'll need a <form> element containing the input fields to make this work (thanks Sergey Ilinsky).
It's not a good practice to redefine standard behaviour, the Enter key should always call the submit button on a form.
Since no one has used addEventListener yet, here is my version. Given the elements:
<input type = "text" id = "txt" />
<input type = "button" id = "go" />
I would use the following:
var go = document.getElementById("go");
var txt = document.getElementById("txt");
txt.addEventListener("keypress", function(event) {
event.preventDefault();
if (event.keyCode == 13)
go.click();
});
This allows you to change the event type and action separately while keeping the HTML clean.
Note that it's probably worthwhile to make sure this is outside of a <form> because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.
Addendum: Thanks to a comment by #ruffin, I've added the missing event handler and a preventDefault to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)
In plain JavaScript,
if (document.layers) {
document.captureEvents(Event.KEYDOWN);
}
document.onkeydown = function (evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 13) {
// For Enter.
// Your function here.
}
if (keyCode == 27) {
// For Escape.
// Your function here.
} else {
return true;
}
};
I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.
Use keypress and event.key === "Enter" with modern JS!
const textbox = document.getElementById("txtSearch");
textbox.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
document.getElementById("btnSearch").click();
}
});
Mozilla Docs
Supported Browsers
One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:
<form onsubmit="Search();" action="javascript:void(0);">
<input type="text" id="searchCriteria" placeholder="Search Criteria"/>
<input type="button" onclick="Search();" value="Search" id="searchBtn"/>
</form>
Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.
To trigger a search every time the enter key is pressed, use this:
$(document).keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
$('#btnSearch').click();
}
}
Try it:
<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>
<script>
window.onload = function() {
document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
if (event.keyCode == 13) {
document.getElementById('btnSearch').click();
}
};
document.getElementById('btnSearch').onclick =doSomething;
}
</script>
onkeydown="javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};"
This is just something I have from a somewhat recent project... I found it on the net, and I have no idea if there's a better way or not in plain old JavaScript.
Although, I'm pretty sure that as long as there is only one field in the form and one submit button, hitting enter should submit the form, even if there is another form on the page.
You can then capture the form onsubmit with js and do whatever validation or callbacks you want.
This is a solution for all the YUI lovers out there:
Y.on('keydown', function() {
if(event.keyCode == 13){
Y.one("#id_of_button").simulate("click");
}
}, '#id_of_textbox');
In this special case I did have better results using YUI for triggering DOM objects that have been injected with button functionality - but this is another story...
In modern, undeprecated (without keyCode or onkeydown) Javascript:
<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">
In Angular2:
(keyup.enter)="doSomething()"
If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.
Also, the id isn't needed - another NG2 way of separating between the view and the model.
Short working pure JS
txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1
txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1
function doSomething() {
console.log('💩');
}
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
This in-case you want also diable the enter button from Posting to server and execute the Js script.
<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
{document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
Nobody noticed the html attibute "accesskey" which is available since a while.
This is a no javascript way to keyboard shortcuts stuffs.
The accesskey attributes shortcuts on MDN
Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser
let client = navigator.userAgent.toLowerCase(),
isLinux = client.indexOf("linux") > -1,
isWin = client.indexOf("windows") > -1,
isMac = client.indexOf("apple") > -1,
isFirefox = client.indexOf("firefox") > -1,
isWebkit = client.indexOf("webkit") > -1,
isOpera = client.indexOf("opera") > -1,
input = document.getElementById('guestInput');
if(isFirefox) {
input.setAttribute("placeholder", "ALT+SHIFT+Z");
} else if (isWin) {
input.setAttribute("placeholder", "ALT+Z");
} else if (isMac) {
input.setAttribute("placeholder", "CTRL+ALT+Z");
} else if (isOpera) {
input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");
} else {'Point me to operate...'}
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
This onchange attempt is close, but misbehaves with respect to browser back then forward (on Safari 4.0.5 and Firefox 3.6.3), so ultimately, I wouldn't recommend it.
<input type="text" id="txtSearch" onchange="doSomething();" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
event.returnValue = false
Use it when handling the event or in the function your event handler calls.
It works in Internet Explorer and Opera at least.
To add a completely plain JavaScript solution that addressed #icedwater's issue with form submission, here's a complete solution with form.
NOTE: This is for "modern browsers", including IE9+. The IE8 version isn't much more complicated, and can be learned here.
Fiddle: https://jsfiddle.net/rufwork/gm6h25th/1/
HTML
<body>
<form>
<input type="text" id="txt" />
<input type="button" id="go" value="Click Me!" />
<div id="outige"></div>
</form>
</body>
JavaScript
// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://stackoverflow.com/a/21814964/1028230
document.addEventListener("DOMContentLoaded", function() {
var go = document.getElementById("go"),
txt = document.getElementById("txt"),
outige = document.getElementById("outige");
// Note that jQuery handles "empty" selections "for free".
// Since we're plain JavaScripting it, we need to make sure this DOM exists first.
if (txt && go) {
txt.addEventListener("keypress", function (e) {
if (event.keyCode === 13) {
go.click();
e.preventDefault(); // <<< Most important missing piece from icedwater
}
});
go.addEventListener("click", function () {
if (outige) {
outige.innerHTML += "Clicked!<br />";
}
});
}
});
For jQuery mobile, I had to do:
$('#id_of_textbox').live("keyup", function(event) {
if(event.keyCode == '13'){
$('#id_of_button').click();
}
});
For those who may like brevity and modern js approach.
input.addEventListener('keydown', (e) => {if (e.keyCode == 13) doSomething()});
where input is a variable containing your input element.
document.onkeypress = function (e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode == 13) {
// Do something here
printResult();
}
};
Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.
To do it with jQuery:
$("#txtSearch").on("keyup", function (event) {
if (event.keyCode==13) {
$("#btnSearch").get(0).click();
}
});
To do it with normal JavaScript:
document.getElementById("txtSearch").addEventListener("keyup", function (event) {
if (event.keyCode==13) {
document.getElementById("#btnSearch").click();
}
});
In jQuery, you can use event.which==13. If you have a form, you could use $('#formid').submit() (with the correct event listeners added to the submission of said form).
$('#textfield').keyup(function(event){
if(event.which==13){
$('#submit').click();
}
});
$('#submit').click(function(e){
if($('#textfield').val().trim().length){
alert("Submitted!");
} else {
alert("Field can not be empty!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="textfield">
Enter Text:</label>
<input id="textfield" type="text">
<button id="submit">
Submit
</button>
These day the change event is the way!
document.getElementById("txtSearch").addEventListener('change',
() => document.getElementById("btnSearch").click()
);
My reusable Vanilla JS solution. so you can change which button gets hit depending on what element/textbox is active.
<input type="text" id="message" onkeypress="enterKeyHandler(event,'sendmessage')" />
<input type="button" id="sendmessage" value="Send"/>
function enterKeyHandler(e,button) {
e = e || window.event;
if (e.key == 'Enter') {
document.getElementById(button).click();
}
}
You can try below code in jQuery.
$("#txtSearch").keyup(function(e) {
e.preventDefault();
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode === 13 || e.key === 'Enter')
{
$("#btnSearch").click();
}
});
I have developed custom javascript to achieve this feature by just adding class
Example: <button type="button" class="ctrl-p">Custom Print</button>
Here Check it out Fiddle
// find elements
var banner = $("#banner-message")
var button = $("button")
// handle click and add class
button.on("click", function(){
if(banner.hasClass("alt"))
banner.removeClass("alt")
else
banner.addClass("alt")
})
$(document).ready(function(){
$(document).on('keydown', function (e) {
if (e.ctrlKey) {
$('[class*="ctrl-"]:not([data-ctrl])').each(function (idx, item) {
var Key = $(item).prop('class').substr($(item).prop('class').indexOf('ctrl-') + 5, 1).toUpperCase();
$(item).attr("data-ctrl", Key);
$(item).append('<div class="tooltip fade top in tooltip-ctrl alter-info" role="tooltip" style="margin-top: -61px; display: block; visibility: visible;"><div class="tooltip-arrow" style="left: 49.5935%;"></div><div class="tooltip-inner"> CTRL + ' + Key + '</div></div>')
});
}
if (e.ctrlKey && e.which != 17) {
var Key = String.fromCharCode(e.which).toLowerCase();
if( $('.ctrl-'+Key).length == 1) {
e.preventDefault();
if (!$('#divLoader').is(":visible"))
$('.ctrl-'+Key).click();
console.log("You pressed ctrl + "+Key );
}
}
});
$(document).on('keyup', function (e) {
if(!e.ctrlKey ){
$('[class*="ctrl-"]').removeAttr("data-ctrl");
$(".tooltip-ctrl").remove();
}
})
});
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
<button class="ctrl-s" title="s">Change color</button><br/><br/>
<span>Press CTRL+S to trigger click event of button</span>
</div>
-- or --
check out running example
https://stackoverflow.com/a/58010042/6631280
Note: on current logic, you need to press Ctrl +
Enter

Categories

Resources