jQuery move cursor to end of text input - javascript

Currently I have an input box which has the value "Current Website"
When they click it I run this function:
function clearMeHttp(formfield) {
if (formfield.defaultValue == formfield.value) {
formfield.value = "http://";
}
};
It works fine if you click into the box, but if you tab into the box it just highlights the word "http://" which defeats the purpose of it unless they hit the right arrow key which I want to avoid.
Thanks!
Here's the other code: <input onblur="restoreMe(this)" onfocus="clearMeHttp(this)" type="text" class="fade" name="website" value="Current website">
restoreMe just fades default value back in gently with jquery

I have changed your code a bit, but uses jquery events instead of inline html.
Full script used:
var defaultVal = 'Current website';
$(function() {
$('.urlCheck').focus(function(e) {
if ($(this).val() == "http://" || $(this).val() == '' || $(this).val() == defaultVal) {
$(this).val('http://');
$(this).select(false);
}
});
$('.urlCheck').keyup(function(e) {
if ($(this).val() == "http://" || $(this).val() == '' || $(this).val() == defaultVal) {
$(this).val('http://');
}
});
$('.urlCheck').blur(function(e) {
$(this).val(defaultVal);
});
});
Working Link : http://jsfiddle.net/29gks/6/
The keyup event is the override for Chrome and Safari

You haven't use jquery so I follow you.
script:
function clearMeHttp(formfield) {
if (formfield.defaultValue == formfield.value) {
formfield.value="";
formfield.style.padding="0 0 0 40";
document.getElementById("http").style.display="block";
}
};
html:
<label id="http" style="float:left;position:absolute;display:none;">http://</label>
<input onblur="restoreMe(this)" onfocus="clearMeHttp(this)" type="text" class="fade" name="website" value="Current website">
That catch your requirement but may be not the way you want

You need to use setSelectionRange() (or selectionStart and selectionEnd) on most browsers and some TextRange shenanigans on IE < 9.
Here's my previous answer to the same question: How to place cursor at end of text in textarea when tabbed into

Related

My function that detects keydown and value does not work

So I have an input bar, where text can be typed in.
I am trying to get the console.log to run as soon as the user clicks on backspace and because of that leaves the input with no value.
Right now the console.log only runs if the backspace is clicked while there isn't any value in the input.
GOAL - The console should ONLY run if clicking on backspace CAUSES the input to be empty.
$("#friendsNames").keydown(function(event){
if (event.keyCode == 8) {
if ($("#friendsNames").val() == "") {
console.log("Works!");
}
}
});
<input type="text" name="namesOfFriend" id="friendsNames" value="" />
I'd recommend not tracking key strokes at all, but monitoring the content of the box using the input event which fires when that content changes:
$("#friendsNames").on('input', function(event) {
if (this.value.length === 0) {
console.log("Works!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="namesOfFriend" id="friendsNames" value="" />
This ensures that any interaction that results in the input becoming empty will trigger your code.
Try to make event on keyup coz if input field empty and you're going to enter first character in it console.log() calls. So try this code or go through mention link JSFiddle
JAVASCRIPT Code -
$("#friendsNames").keyup(function(event) {
if (event.keyCode == 8 && $(this).val() == "") {
console.log("Works!");
}
});
$("#friendsNames").keypress(function(event) {
if (event.keyCode == 8 || $(this).val() != "") {
alert("Works!");
}
});
As I understand, you want console.log to execute only where this is any value in the input box, else it shouldn't execute, right? Based on this, below is the code:
$("#friendsNames").on('input', function(){
var inputValue = $(this).val();
if(inputValue.length == 0)
console.log("Works!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="namesOfFriend" id="friendsNames" value="" />

Showing Placeholder text for password field in IE

I know there is a ton of placeholder questions, but I am trying to perfect mine.
My current code works great and does what it's supposed to. The problem is, when I go to place the "password" placeholder, it puts the placeholder in the masking characters. Any ideas on how to get around that?
$(function() {
if(!$.support.placeholder) {
var active = document.activeElement;
$(':text').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
var active = document.activeElement;
$(':password').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':password').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});
My field for the pass:
<div id="loginform_pass"><input class="login" tabindex="2" type="password" placeholder="Password" name="password" maxlength="30"></div>
You could also try this... it detects that the browser does not have support for placeholder and works for all input types
function FauxPlaceholder() {
if(!ElementSupportAttribute('input','placeholder')) {
$("input[placeholder]").each(function() {
var $input = $(this);
$input.after('<input id="'+$input.attr('id')+'-faux" style="display:none;" type="text" value="' + $input.attr('placeholder') + '" />');
var $faux = $('#'+$input.attr('id')+'-faux');
$faux.show().attr('class', $input.attr('class')).attr('style', $input.attr('style'));
$input.hide();
$faux.focus(function() {
$faux.hide();
$input.show().focus();
});
$input.blur(function() {
if($input.val() === '') {
$input.hide();
$faux.show();
}
});
});
}
}
function ElementSupportAttribute(elm, attr) {
var test = document.createElement(elm);
return attr in test;
}
Could you just swap out the original text field with a password field?
$('#pass').focus(
function(){
var pass = $('<input id="pass" type="password">');
$(this).replaceWith(pass);
pass.focus();
}
);
<input id="pass" type="text" value="Passowrd">
http://jsfiddle.net/UrNFV/
I ran into this problem with IE before. Here's my solution :)
http://jsfiddle.net/mNchn/
If I'm understanding this right, you want the field to say "Password" when nothing has been typed into it; however, "Password" gets displayed as "********".
A decent fix to that (which also degrades gracefully, depending on how you code it) is to:
Put a LABEL before the password INPUT. Set the LABEL's text to "Password", and set its for attribute to point to the INPUT's ID, so that the INPUT is focused when the LABEL is clicked.
Use CSS to position the LABEL on top of the INPUT, so that they overlap, and it looks like "Password" is inside of the INPUT.
Make it so that the LABEL is only visible when some CSS class (.showMe, for example) is applied to it.
Use JavaScript to hide the LABEL
...if the INPUT's value is an empty string
...or if the user has selected (focused) the INPUT.
Depending on whether or not you want to be able to dynamically change the text inside the placeholder, your simplest solution might be to have the placeholder text be an image.
input {
background: url(_img/placeholder.png) 50% 5px no-repeat;
.
.
.
}
input:focus {
background: none;
}
Clearly there are many different ways of using this method, and you will have to use some kind of a fix to get :focus to work on the browsers that don't support it.
Here my plugin :
if(jQuery.support.placeholder==false){
// No default treatment
$('[placeholder]').focus(function(){
if($(this).val()==$(this).attr('placeholder'))
$(this).val('');
if($(this).data('type')=='password')
$(this).get(0).type='password';
});
$('[placeholder]').blur(function(){
if($(this).val()==''){
if($(this).attr('type')=='password'){
$(this).data('type','password').get(0).type='text';
}
$(this).val($(this).attr('placeholder'));
}
}).blur();
}
I had the same problem so i wrote a little plugin
$.fn.passLabel = function(){
var
T = $(this),
P = T.find('input[type=password]'),
V = pass.val();
P.attr('type','text');
P.focus(function(){
if(V == "")
P.attr('type','password');
});
}
now you just call it for the from at it will find all input fields with the password
attribute.
eg.
$('form').passLabel();
A bit late however same here, i was working on the issue too IE9 doesnot show the password placeholder as text, in almost all the answers on the internet some suggest changing the type some but if u do this u will have another issue on the login page like when you will see with double click on password field as its type changed to text from password, btw it works with prop. e.g. prop("type","password") if you want to change the type of an element.
on the other hand i think most answers come from a single solution its like focus and blur actions of elements. but when u apply this plugin other text fields will also be effected there is no specific or i can say generlized solution, i have still a minor issue on the login page with the password field but its showing the text correctly. anyway. here is how i have configured, copied,changed and/or another inherited anwers here.
(function($) {
$.fn.placeholder = function() {
$('input[placeholder], textarea[placeholder]').focus(function() {
var input = $(this);
if (input.val() === input.attr('placeholder')) {
if (input.prop("id") === "password") {
input.prop("type", "password");
}
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() === '' || input.val() === input.attr('placeholder')) {
input.addClass('placeholder');
if (input.prop("type") === "password") {
input.prop("type", "text");
}
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('input[placeholder], textarea[placeholder]').each(function() {
var input = $(this);
if (input.val() === input.attr('placeholder')) {
input.val('');
}
});
});
};
})(jQuery);
still an active prolem ... :D

How do I convert Enter to Tab (with focus change) in IE9? It worked in IE8

I have a text input with an onkeydown event handler that converts <Enter> to <Tab> by changing the event's keyCode from 13 to 9.
<input type="text" onkeydown="enterToTab(event);" onchange="changeEvent(this);"
name="" value="" />
<!-- Other inputs exist as created via the DOM, but they are not sibling elements. -->
Javascript:
function enterToTab(myEvent) {
if (myEvent.keyCode == 13) {
myEvent.keyCode = 9;
}
}
function changeEvent(myInput) { var test = "hello"; }
In IE8, this caused the onchange event to fire, but that doesn't happen in IE9. Instead, the input field retains focus. How I can I make that happen? (It works in Firefox 3.6 and Chrome 10.0.) This even works in Browser Mode IE9 if I set the Document Mode to "IE8 standards". But it won't work with a Document Mode of "IE9 standards". (My DocType is XHTML 1.0 Transitional.)
Since it works in IE7 & 8, could this be a bug in IE9 that will get fixed?
Please note: I cannot use input.blur() or manually set a new focus, which is advised by all the other solutions that I've read. I've already tried onkeypress and onkeyup with no luck. I need a generic solution that will cause the web app to literally behave as though I'd hit <Tab>. Also, I don't have jQuery, however, Dojo 1.5 is available to me.
Also note: I KNOW this is "wrong" behavior, and that Enter ought to submit the form. However, my client's staff originally come from a green screen environment where Enter moves them between fields. We must retain the same UI. It is what it is.
UPDATE: I found a difference between IE8 & IE9. In IE8, my setting of myEvent.keyCode holds. In IE9, it does NOT. I can update window.event.keyCode, and it will hold, but that won't affect what happens later. Argh... Any ideas?
Looks like IE9 events are immutable. Once they've been fired you can't change the properties on them, just preventDefault() or cancel them. So you best option is to cancel any "enter" events and re-dispatch a new DOM event from the text input.
Example
function enterToTab(event){
if(event.keyCode == 13){
var keyEvent = document.createEvent("Event");
// This is a lovely method signature
keyEvent.initKeyboardEvent("onkeydown", true, true, window, 9, event.location, "", event.repeat, event.locale);
event.currentTarget.dispatchEvent(keyEvent);
// you may want to prevent default here
}
}
Here's the MSDN documentation around IE9 DOM events:
Event Object - http://msdn.microsoft.com/en-us/library/ms535863(v=vs.85).aspx
createEvent - http://msdn.microsoft.com/en-us/library/ff975304(v=vs.85).aspx
initialize a Keyboard Event - http://msdn.microsoft.com/en-us/library/ff975297(v=vs.85).aspx
Here is a different idea; change the on submit so that it calls a function instead of processing the form. in the function check all the fields to see if they are blank, then focus on the next field that doesn't have a value.
So they type a value into field 1, hit enter, and the function runs. it sees that field 1 is full, but field 2 isn't, so focus on field 2.
Then when all the fields are full, submit the form for processing.
If the form has fields that can be blank, you could use a boolean array that would keep track of which fields received focus using the onfocus() event.
Just an outside the box idea.
The previous IE-version allowed the non standard writable event.keyCode property, IE9 now conforms to the standards.
You may want to consider the functionality you are after: you want to make the enter key behave like the tab key, i.e. moving the focus to the next (text) input field. There are more ways to do that. One of them is using the tabindex attribute of the text input fields. If you order the fields in your form using this tabindex attribute, the functions I present here may yield the same result as your previous keyCode method. Here are two functions I tested in this jsfiddle. An (text) input field now looks like:
<input type="text"
onkeypress="nextOnEnter(this,event);"
name="" value=""
tabindex="1"/>
the functions to use for tabbing:
function nextOnEnter(obj,e){
e = e || event;
// we are storing all input fields with tabindex attribute in
// a 'static' field of this function using the external function
// getTabbableFields
nextOnEnter.fields = nextOnEnter.fields || getTabbableFields();
if (e.keyCode === 13) {
// first, prevent default behavior for enter key (submit)
if (e.preventDefault){
e.preventDefault();
} else if (e.stopPropagation){
e.stopPropagation();
} else {
e.returnValue = false;
}
// determine current tabindex
var tabi = parseInt(obj.getAttribute('tabindex'),10);
// focus to next tabindex in line
if ( tabi+1 < nextOnEnter.fields.length ){
nextOnEnter.fields[tabi+1].focus();
}
}
}
// returns an array containing all input text/submit fields with a
// tabindex attribute, in the order of the tabindex values
function getTabbableFields(){
var ret = [],
inpts = document.getElementsByTagName('input'),
i = inpts.length;
while (i--){
var tabi = parseInt(inpts[i].getAttribute('tabindex'),10),
txtType = inpts[i].getAttribute('type');
// [txtType] could be used to filter out input fields that you
// don't want to be 'tabbable'
ret[tabi] = inpts[i];
}
return ret;
}
If you don't want to use tabindex and all your input fields are 'tabbable', see this jsfiddle
[EDIT] edited functions (see jsfiddles) to make use of event delegation and make it all work in Opera too. And this version imitates shift-TAB too.
The code above causes problems. Here's some code that will help you. Works on IE9, FF5 etc.
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
And then you should just create your input texts or whatever
<input type="text" id="1" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="2" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="3" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="4" onkeydown="return tabOnEnter(this,event)"/>
A <button> element on a page will cause this problem.
In IE9 a <button> element takes the focus when Enter is pressed. Any submit or reset button will cause the problem too. If you are not using submit/reset then you can fix this by changing all buttons to <input type="button"> or by setting the button's type attribute to button. i.e.
<button type="button">Click me!</button>
Alternatively as per KooiInc's answer, you can edit your javascript to use event.preventDefault(); to prevent the Enter key acting this way, and explicitly call focus() on the next element in the tab order.
Here is some test code I wrote that demonstrates the problem with the button element (note the blue focus ring on button3 in IE9):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>IE problem with Enter key and <button> elements</title>
</head>
<body>
<script>
function press(event) {
if (event.keyCode == 13) {
document.getElementById('input2').focus();
// In IE9 the focus shifts to the <button> unless we call preventDefault(). Uncomment following line for IE9 fix. Alternatively set type="button" on all button elements and anything else that is a submit or reset too!.
// event.preventDefault && event.preventDefault();
}
}
</script>
<input id="input1" type="text" onkeypress="press(event)" value="input1. Press enter here." /><br />
<input id="input2" type="text" value="input2. Press enter here." /><br />
<input id="button1" type="button" value='I am an <input type="button">' /><br />
<button id="button2" type="button">I am a <button type="button"></button><br />
<button id="button3">I am a <button>. I get focus when enter key pressed in IE9 - wooot!</button><span>As per Microsoft docs on <a target="_tab" href="http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx">BUTTON.type</a> it is because type defaults to submit.</span>
</body>
</html>
Mike Fdz's code is superb. In order to skip over hidden fields, you may want to change the line
return form.elements[++e % form.elements.length];
to this:
e++;
while (form.elements[e % form.elements.length].type == "hidden") {
e++;
}
return form.elements[e % form.elements.length];
Use onpaste along with onkeypress like
Consider you have wrriten a javascript function which checks the text lenght so we will need to validate it on key press like as below
<asp:TextBox ID="txtInputText" runat="server" Text="Please enter some text" onpaste="return textboxMultilineMaxNumber(this,1000);" onkeypress="return textboxMultilineMaxNumber(this,1000);"></asp:TextBox>
onkeypress will work in both FF and IE
but if you try to do ctr+V in textbox then onpaste will handle in IE in FF onkeypress takes care of it
This is what I have done with what I found over the internet :
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") || (node.type=="radio")))
{
getNextElement(node).focus();
return false;
}
}
function getNextElement(field)
{
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
e++;
while (form.elements[e % form.elements.length].type == "hidden")
{
e++;
}
return form.elements[e % form.elements.length];;
}
To prevent a "submit event" triggered by Enter-Keyboard in your Form in IE9, retire any button inside the form area. Place him (button) in outside of form's area.
function enterAsTab() {
var keyPressed = event.keyCode; // get the Key that is pressed
if (keyPressed == 13)
{
//case the KeyPressed is the [Enter]
var inputs = $('input'); // storage a array of Inputs
var a = inputs.index(document.activeElement);
//get the Index of Active Element Input inside the Inputs(array)
if (inputs[a + 1] !== null)
{
// case the next index of array is not null
var nextBox = inputs[a + 1];
nextBox.focus(); // Focus the next input element. Make him an Active Element
event.preventDefault();
}
return false;
}
else {return keyPressed;}
}
<HTML>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onKeyPress="return enterAsTab();">
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
</body>
</HTML>

JQuery Default text on empty text box

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.

Enter key press behaves like a Tab in Javascript

I'm looking to create a form where pressing the enter key causes focus to go to the "next" form element on the page. The solution I keep finding on the web is...
<body onkeydown="if(event.keyCode==13){event.keyCode=9; return event.keyCode}">
Unfortunately, that only seems to work in IE. So the real meat of this question is if anybody knows of a solution that works for FF and Chrome? Additionally, I'd rather not have to add onkeydown events to the form elements themselves, but if that's the only way, it will have to do.
This issue is similar to question 905222, but deserving of it's own question in my opinion.
Edit: also, I've seen people bring up the issue that this isn't good style, as it diverges from form behavior that users are used to. I agree! It's a client request :(
I used the logic suggested by Andrew which is very effective. And this is my version:
$('body').on('keydown', 'input, select', function(e) {
if (e.key === "Enter") {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
KeyboardEvent's keycode (i.e: e.keycode) depreciation notice :- https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
The simplest vanilla JS snippet I came up with:
document.addEventListener('keydown', function (event) {
if (event.keyCode === 13 && event.target.nodeName === 'INPUT') {
var form = event.target.form;
var index = Array.prototype.indexOf.call(form, event.target);
form.elements[index + 1].focus();
event.preventDefault();
}
});
Works in IE 9+ and modern browsers.
Map [Enter] key to work like the [Tab] key
I've rewritten Andre Van Zuydam's answer, which didn't work for me, in jQuery. This caputures both Enter and Shift+Enter. Enter tabs forward, and Shift+Enter tabs back.
I've also rewritten the way self is initialized by the current item in focus. The form is also selected that way. Here's the code:
// Map [Enter] key to work like the [Tab] key
// Daniel P. Clark 2014
// Catch the keydown for the entire document
$(document).keydown(function(e) {
// Set self as the current item in focus
var self = $(':focus'),
// Set the form by the current item in focus
form = self.parents('form:eq(0)'),
focusable;
// Array of Indexable/Tab-able items
focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');
function enterKey(){
if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key
// If not a regular hyperlink/button/textarea
if ($.inArray(self, focusable) && (!self.is('a,button'))){
// Then prevent the default [Enter] key behaviour from submitting the form
e.preventDefault();
} // Otherwise follow the link/button as by design, or put new line in textarea
// Focus on the next item (either previous or next depending on shift)
focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();
return false;
}
}
// We need to capture the [Shift] key and check the [Enter] key either way.
if (e.shiftKey) { enterKey() } else { enterKey() }
});
The reason textarea
is included is because we "do" want to tab into it. Also, once in, we don't want to stop the default behavior of Enter from putting in a new line.
The reason a and button
allow the default action, "and" still focus on the next item, is because they don't always load another page. There can be a trigger/effect on those such as an accordion or tabbed content. So once you trigger the default behavior, and the page does its special effect, you still want to go to the next item since your trigger may have well introduced it.
Thank you for the good script.
I have just added the shift event on the above function to go back between elements, I thought someone may need this.
$('body').on('keydown', 'input, select, textarea', function(e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
, prev
;
if (e.shiftKey) {
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
prev = focusable.eq(focusable.index(this)-1);
if (prev.length) {
prev.focus();
} else {
form.submit();
}
}
}
else
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
This worked for me:
$(document).on('keydown', ':tabbable', function(e) {
if (e.key === "Enter") {
e.preventDefault();
var $canfocus = $(':tabbable:visible');
var index = $canfocus.index(document.activeElement) + 1;
if (index >= $canfocus.length) index = 0;
$canfocus.eq(index).focus();
}
});
Changing this behaviour actually creates a far better user experience than the default behaviour implemented natively. Consider that the behaviour of the enter key is already inconsistent from the user's point of view, because in a single line input, enter tends to submit a form, while in a multi-line textarea, it simply adds a newline to the contents of the field.
I recently did it like this (uses jQuery):
$('input.enterastab, select.enterastab, textarea.enterastab').live('keydown', function(e) {
if (e.keyCode==13) {
var focusable = $('input,a,select,button,textarea').filter(':visible');
focusable.eq(focusable.index(this)+1).focus();
return false;
}
});
This is not terribly efficient, but works well enough and is reliable - just add the 'enterastab' class to any input element that should behave in this way.
I reworked the OPs solution into a Knockout binding and thought I'd share it. Thanks very much :-)
Here's a Fiddle
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js" type="text/javascript"></script>
</head>
<body>
<div data-bind="nextFieldOnEnter:true">
<input type="text" />
<input type="text" />
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" />
<input type="text" />
</div>
<script type="text/javascript">
ko.bindingHandlers.nextFieldOnEnter = {
init: function(element, valueAccessor, allBindingsAccessor) {
$(element).on('keydown', 'input, select', function (e) {
var self = $(this)
, form = $(element)
, focusable
, next
;
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
var nextIndex = focusable.index(this) == focusable.length -1 ? 0 : focusable.index(this) + 1;
next = focusable.eq(nextIndex);
next.focus();
return false;
}
});
}
};
ko.applyBindings({});
</script>
</body>
</html>
Here is an angular.js directive to make enter go to the next field using the other answers as inspiration. There is some, perhaps, odd looking code here because I only use the jQlite packaged with angular. I believe most of the features here work in all browsers > IE8.
angular.module('myapp', [])
.directive('pdkNextInputOnEnter', function() {
var includeTags = ['INPUT', 'SELECT'];
function link(scope, element, attrs) {
element.on('keydown', function (e) {
// Go to next form element on enter and only for included tags
if (e.keyCode == 13 && includeTags.indexOf(e.target.tagName) != -1) {
// Find all form elements that can receive focus
var focusable = element[0].querySelectorAll('input,select,button,textarea');
// Get the index of the currently focused element
var currentIndex = Array.prototype.indexOf.call(focusable, e.target)
// Find the next items in the list
var nextIndex = currentIndex == focusable.length - 1 ? 0 : currentIndex + 1;
// Focus the next element
if(nextIndex >= 0 && nextIndex < focusable.length)
focusable[nextIndex].focus();
return false;
}
});
}
return {
restrict: 'A',
link: link
};
});
Here's how I use it in the app I'm working on, by just adding the pdk-next-input-on-enter directive on an element. I am using a barcode scanner to enter data into fields, the default function of the scanner is to emulate a keayboard, injecting an enter key after typing the data of the scanned barcode.
There is one side-effect to this code (a positive one for my use-case), if it moves focus onto a button, the enter keyup event will cause the button's action to be activated. This worked really well for my flow as the last form element in my markup is a button that I want activated once all the fields have been "tabbed" through by scanning barcodes.
<!DOCTYPE html>
<html ng-app=myapp>
<head>
<script src="angular.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-controller="LabelPrintingController">
<div class='.container' pdk-next-input-on-enter>
<select ng-options="p for p in partNumbers" ng-model="selectedPart" ng-change="selectedPartChanged()"></select>
<h2>{{labelDocument.SerialNumber}}</h2>
<div ng-show="labelDocument.ComponentSerials">
<b>Component Serials</b>
<ul>
<li ng-repeat="serial in labelDocument.ComponentSerials">
{{serial.name}}<br/>
<input type="text" ng-model="serial.value" />
</li>
</ul>
</div>
<button ng-click="printLabel()">Print</button>
</div>
</body>
</html>
Try this...
$(document).ready(function () {
$.fn.enterkeytab = function () {
$(this).on('keydown', 'input,select,text,button', function (e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
;
if (e.keyCode == 13) {
focusable = form.find('input,a,select').filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
//if disable try get next 10 fields
if (next.is(":disabled")){
for(i=2;i<10;i++){
next = focusable.eq(focusable.index(this) + i);
if (!next.is(":disabled"))
break;
}
}
next.focus();
}
return false;
}
});
}
$("form").enterkeytab();
});
I've had a similar problem, where I wanted to press + on the numpad to tab to the next field. Now I've released a library that I think will help you.
PlusAsTab: A jQuery plugin to use the numpad plus key as a tab key equivalent.
Since you want enter/↵ instead, you can set the options. Find out which key you want to use with the jQuery event.which demo.
JoelPurra.PlusAsTab.setOptions({
// Use enter instead of plus
// Number 13 found through demo at
// https://api.jquery.com/event.which/
key: 13
});
// Matches all inputs with name "a[]" (needs some character escaping)
$('input[name=a\\[\\]]').plusAsTab();
You can try it out yourself in the PlusAsTab enter as tab demo.
function return2tab (div)
{
document.addEventListener('keydown', function (ev) {
if (ev.key === "Enter" && ev.target.nodeName === 'INPUT') {
var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]';
let ol= div.querySelectorAll(focusableElementsString);
for (let i=0; i<ol.length; i++) {
if (ol[i] === ev.target) {
let o= i<ol.length-1? ol[i+1]: o[0];
o.focus(); break;
}
}
ev.preventDefault();
}
});
}
I have it working in only JavaScript. Firefox won't let you update the keyCode, so all you can do is trap keyCode 13 and force it to focus on the next element by tabIndex as if keyCode 9 was pressed. The tricky part is finding the next tabIndex. I have tested this only on IE8-IE10 and Firefox and it works:
function ModifyEnterKeyPressAsTab(event)
{
var caller;
var key;
if (window.event)
{
caller = window.event.srcElement; //Get the event caller in IE.
key = window.event.keyCode; //Get the keycode in IE.
}
else
{
caller = event.target; //Get the event caller in Firefox.
key = event.which; //Get the keycode in Firefox.
}
if (key == 13) //Enter key was pressed.
{
cTab = caller.tabIndex; //caller tabIndex.
maxTab = 0; //highest tabIndex (start at 0 to change)
minTab = cTab; //lowest tabIndex (this may change, but start at caller)
allById = document.getElementsByTagName("input"); //Get input elements.
allByIndex = []; //Storage for elements by index.
c = 0; //index of the caller in allByIndex (start at 0 to change)
i = 0; //generic indexer for allByIndex;
for (id in allById) //Loop through all the input elements by id.
{
allByIndex[i] = allById[id]; //Set allByIndex.
tab = allByIndex[i].tabIndex;
if (caller == allByIndex[i])
c = i; //Get the index of the caller.
if (tab > maxTab)
maxTab = tab; //Get the highest tabIndex on the page.
if (tab < minTab && tab >= 0)
minTab = tab; //Get the lowest positive tabIndex on the page.
i++;
}
//Loop through tab indexes from caller to highest.
for (tab = cTab; tab <= maxTab; tab++)
{
//Look for this tabIndex from the caller to the end of page.
for (i = c + 1; i < allByIndex.length; i++)
{
if (allByIndex[i].tabIndex == tab)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
//Look for the next tabIndex from the start of page to the caller.
for (i = 0; i < c; i++)
{
if (allByIndex[i].tabIndex == tab + 1)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
//Continue searching from the caller for the next tabIndex.
}
//The caller was the last element with the highest tabIndex,
//so find the first element with the lowest tabIndex.
for (i = 0; i < allByIndex.length; i++)
{
if (allByIndex[i].tabIndex == minTab)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
}
}
To use this code, add it to your html input tag:
<input id="SomeID" onkeydown="ModifyEnterKeyPressAsTab(event);" ... >
Or add it to an element in javascript:
document.getElementById("SomeID").onKeyDown = ModifyEnterKeyPressAsTab;
A couple other notes:
I only needed it to work on my input elements, but you could extend it to other document elements if you need to. For this, getElementsByClassName is very helpful, but that is a whole other topic.
A limitation is that it only tabs between the elements that you have added to your allById array. It does not tab around to the other things that your browser might, like toolbars and menus outside your html document. Perhaps this is a feature instead of a limitation. If you like, trap keyCode 9 and this behavior will work with the tab key too.
You can use my code below, tested in Mozilla, IE, and Chrome
// Use to act like tab using enter key
$.fn.enterkeytab=function(){
$(this).on('keydown', 'input, select,', function(e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
;
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
alert("wd");
//form.submit();
}
return false;
}
});
}
How to Use?
$("#form").enterkeytab(); // enter key tab
If you can I would reconsider doing this: the default action of pressing <Enter> while in a form submits the form and anything you do to change this default action / expected behaviour could cause some usability issues with the site.
Vanilla js with support for Shift + Enter and ability to choose which HTML tags are focusable. Should work IE9+.
onKeyUp(e) {
switch (e.keyCode) {
case 13: //Enter
var focusableElements = document.querySelectorAll('input, button')
var index = Array.prototype.indexOf.call(focusableElements, document.activeElement)
if(e.shiftKey)
focus(focusableElements, index - 1)
else
focus(focusableElements, index + 1)
e.preventDefault()
break;
}
function focus(elements, index) {
if(elements[index])
elements[index].focus()
}
}
Here's what I came up with.
form.addEventListener("submit", (e) => { //On Submit
let key = e.charCode || e.keyCode || 0 //get the key code
if (key = 13) { //If enter key
e.preventDefault()
const inputs = Array.from(document.querySelectorAll("form input")) //Get array of inputs
let nextInput = inputs[inputs.indexOf(document.activeElement) + 1] //get index of input after the current input
nextInput.focus() //focus new input
}
}
Many answers here uses e.keyCode and e.which that are deprecated.
Instead you should use e.key === 'Enter'.
Documentation: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
I'm sorry but I can't test these snippets just now. Will come back later after testing it.
With HTML:
<body onkeypress="if(event.key==='Enter' && event.target.form){focusNextElement(event); return false;}">
With jQuery:
$(window).on('keypress', function (ev)
{
if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev)
}
And with Vanilla JS:
document.addEventListener('keypress', function (ev) {
if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev);
});
You can take focusNextElement() function from here:
https://stackoverflow.com/a/35173443/3356679
Easiest way to solve this problem with the focus function of JavaScript as follows:
You can copy and try it # home!
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input id="input1" type="text" onkeypress="pressEnter()" />
<input id="input2" type="text" onkeypress="pressEnter2()" />
<input id="input3" type="text"/>
<script type="text/javascript">
function pressEnter() {
// Key Code for ENTER = 13
if ((event.keyCode == 13)) {
document.getElementById("input2").focus({preventScroll:false});
}
}
function pressEnter2() {
if ((event.keyCode == 13)) {
document.getElementById("input3").focus({preventScroll:false});
}
}
</script>
</body>
</html>
I had a problem to use enter key instead of Tab in React js .The solution of anjana-silva is working fine and just some small issue for input date and autocomplete as I am using MUI . So I change it a bit and add arrow keys (left/right) as well .
install jquery using npm
npm install jquery --save
write the below in App.js If you want to have this behavior In the whole of your application
import $ from 'jquery';
useEffect(() => {
$('body').on('keydown', 'input, select,button', function (e) {
if (e.keyCode === 13 || e.keyCode === 39) {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input,a,select,button,textarea').filter(':visible:not([readonly]):enabled');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
}
return false;
}
if (e.keyCode === 37) {
var self = $(this), form = self.parents('form:eq(0)'), focusable, prev;
focusable = form.find('input,a,select,button,textarea').filter(':visible:not([readonly]):enabled');
prev = focusable.eq(focusable.index(this) - 1);
if (prev.length) {
prev.focus();
}
return false;
}
});
}, []);
I had a simular need.
Here is what I did:
<script type="text/javascript" language="javascript">
function convertEnterToTab() {
if(event.keyCode==13) {
event.keyCode = 9;
}
}
document.onkeydown = convertEnterToTab;
</script>
In all that cases, only works in Chrome and IE, I added the following code to solve that:
var key = (window.event) ? e.keyCode : e.which;
and I tested the key value on if keycode equals 13
$('body').on('keydown', 'input, select, textarea', function (e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
;
var key = (window.event) ? e.keyCode : e.which;
if (key == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
} else {
focusable.click();
}
return false;
}
});
$("#form input , select , textarea").keypress(function(e){
if(e.keyCode == 13){
var enter_position = $(this).index();
$("#form input , select , textarea").eq(enter_position+1).focus();
}
});
You could programatically iterate the form elements adding the onkeydown handler as you go. This way you can reuse the code.

Categories

Resources