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.
http://codepen.io/abdulahhamzic/pen/YqMQwB
How do I make it so that when I press enter on a text input, it calls a function? I tried using this:
<input type="text" onkeypress="clickPress()">
But the problem is I only want to press enter to call that function, not press any key. How do I achieve that?
2022 Update: onkeypress is deprecated.
You can use onKeyDown instead
What you'd want to do is check whether the event's key is the enter key:
In your html, add the event argument
<input type="text" onkeypress="clickPress(event)">
And in your handler, add an event parameter
function clickPress(event) {
if (event.keyCode == 13) {
// do something
}
}
2022 Update: event.keyCode is deprecated on many browsers.
You should do this now:
function clickPress(event) {
if (event.key == "Enter") {
// do something
}
}
Use a form instead (the submit event only runs once instead of every key press):
// Attach the event handler to the form element
document.querySelector('.js-form')?.addEventListener('submit', e => {
e.preventDefault();
alert(e.currentTarget.myText.value);
});
<form class="js-form">
<input type="text" name="myText">
</form>
The Enter button has a keyCode of 13, so you can use the keypress event using jQuery
$("input").keypress(function(event) {
if (event.which == 13) {
alert("Enter was pressed");
}
});
or, in pure javascript:
<input type="text" onkeypress="clickPress(event)">
function clickPress(event) {
if (event.keyCode == 13) {
// do something
}
}
Get the event's keycode and test if it's enter (keycode 13)
<script>
function clickPress(e){
if (event.keyCode == 13) {
// Enter was pressed
alert("enter");
}
}
</script>
<input type="text" onkeypress="clickPress(event)" />
jsfiddle
There could be several "better" ways to do what you want to do but just for the sake of simplicity, you could do this:
<input type="text" id="txt">
Instead of listening to the onkeypress you could attach an event listener within the <script></script> tags and do this:
var myText = document.getElementById("txt");
myText.addEventListener("keyup", function(e) {
if (e.which === 13) {
//The keycode for enter key is 13
alert(e.target.value);
}
});
And yeah this is definitely a duplicate question.
<form name='qform'>
<textarea name='q' rows='3' cols='60' wrap='hard' id='q' onkeydown="if (event.keyCode == 13) document.getElementById('clickit').click()"></textarea>
<input type='button' value='search' id='clickit' onclick="get();">
</form>
I have this form... it doesn't have a submit button because I am using jquery and under this form is a div area where the results will be shown. It is a search engine that does not have an input box but instead has a textarea. This is because it will be a multiple word searcher.
The problem is that if I press enter, the query is submitted and everything is ok ... but the focus on textarea goes down one line and that is a problem for me.
Basically I want the enter to have that one function only(submit) end nothing else.
$(document).ready(function() {
$('textarea').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
});
Why not just use <input type="text"> if you don't want multiple lines? You mentioned it will be a "multiple word searcher". Why does this require a <textarea>?
Update
Try this
$('textarea').bind('keypress', function(e) {
if ((e.keyCode || e.which) == 13) {
$(this).parents('form').submit();
return false;
}
});
In the jquery function, use event.preventdefault and next do what you like.
For example
<script>
$("a").click(function(event) {
event.preventDefault();
//Do your logic here
});
</script>
http://api.jquery.com/event.preventDefault/
Pure javascript:
document.addEventListener('keypress', function (e) {
if (e.keyCode === 13 || e.which === 13) {
e.preventDefault();
return false;
}
})
I have a email form text box that while it is empty I would like it to have the value "E-Mail" And when you click on it the text goes away. If someone clicks on it and doesn't enter text. on Blur I would like for it to return to having the default text.
I have been trying a few things but nothing is working. Could someone please point me in the right direction?
Or you could just use the placeholder html5 attribute:
<input type="text" id="keyword" name="keyword" placeholder="Type keyword here" />
it goes something like this
$('#yourElement').focus(function(){
//Check val for email
if($(this).val() == 'E-Mail'){
$(this).val('');
}
}).blur(function(){
//check for empty input
if($(this).val() == ''){
$(this).val('E-Mail');
}
});
you can use the placeholder attribute and then us this jquery as backup for IE
<input type="text" id="keyword" name="keyword" placeholder="The watermark" value='The watermark' class="watermark"/>
$(document).ready(function () {
$('.watermark').focus(function () {
if ($(this).val() == $(this).attr('placeholder')) {
$(this).val('');
}
}).blur(function () {
if ($(this).val() == '') {
$(this).val($(this).attr('placeholder'));
}
});
});
It's pretty straightforward. Just erase the value onfocus, and then (if the value is still empty) refill it onblur.
Call the below function and pass it two args: slightLabel(jQuery('#email_field'), 'email');
function slightLabel(input, text) {
jQuery(input).val(text);
jQuery(input).data('defaultText', text);
jQuery(input).focus(function(){
if(!jQuery(this).data('touched'))
{
jQuery(this).data('touched', true);
jQuery(input).val('');
}
});
// the part to restore the original text in
jQuery(input).blur(function(){
if(jQuery(this).val() == '')
{
jQuery(this).val(jQuery(this).data('defaultText'));
}
});
}
You could use one of the watermark plugins of jquery that do just that. I use a watermark plugin that has the following code
$.fn.watermark = function (c, t) {
var e = function (e) {
var i = $(this);
if (!i.val()) {
var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c);
i.replaceWith($c);
$c.focus(function () {
$c.replaceWith(i); setTimeout(function () { i.focus(); }, 1);
})
.change(function (e) {
i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i);
})
.closest('form').submit(function () {
$c.replaceWith(i);
});
}
};
return $(this).live('blur change', e).change();
};
Callable in jquery by setting the class of the input textbox to watermark like this
<input type="text" id="keyword" name="keyword" class="watermark" style="width: 250px"
title="Type keyword here" />
The title is what will be displayed in the watermark.
Use this Jquery-placeholder plugin
Using this plugin makes it possible to also use the placeholder attribute in non HTML5 capable browsers.
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