How to write key events when the cursor inside the textfield - javascript

Hi I am writing key events for remote for that screen, ups and downs working properly, the problem is when the cursor is inside the text field my key events is not working.
if anybody knows about key events plz help me.
Controller.js
var unFocusText = function(){
$("#search_all")[0].blur();
};
case PV.yoohu.appConstants.keyCodes.BACK:
case PV.yoohu.appConstants.keyCodes.ESC:
break;
case PV.yoohu.appConstants.keyCodes.SELECT:
if (_isSearchItemHighlighted == 8) {
$("#search_all")[0].focus();
}
break;
case PV.yoohu.appConstants.keyCodes.DOWN:
if (searchScreen) {
if (0 <= _isSearchItemHighlighted && _isSearchItemHighlighted <= $scope.searchFilters.length-1) {
isSearchItemHighlighted = 8;
}
}
break;
case PV.yoohu.appConstants.keyCodes.RIGHT:
if (_isSearchItemHighlighted == 8) {
_isSearchItemHighlighted = 9;
unFocusText();
}
break;
case PV.yoohu.appConstants.keyCodes.UP:
if (_isSearchItemHighlighted == 8) {
_isSearchItemHighlighted = 0;
unFocusText();
}
<div id="searchCategory">
<div id="searchFilter" ng-repeat="item in searchFilters">
<input id="searchFilternames" type="radio" ng-model="selectedFilter.name"
value="{{item.name}}"
ng-class="{'selected-search-asset-border': isSearchItemHighlighted($index)}"
ng-checked="isItemChecked(item, $index)"/><span
ng-bind="item.name"></span>
</div>
</div>
<input type="text" id="search_all" class="input" placeholder="enter text" ng-class="{'selected-search-asset-border': isSearchItemHighlighted(8)}"
/>
<input type="image" id="searchButton"class="searchImage" src="resources/search1.png"
ng-class="{'selected-search-asset-border': isSearchItemHighlighted(9)}" ng-click="availableSearchList()" />
index no of the search textfield is 8, if i press enter, when the Red Border in Search textfield the cursor will be focused, but after that my key events are not working.
Actually i wants to move controller to right and up from the text field.
What is the wrong in my code, Please help me.

The best solution is:
$("your_input").keyup(function (e) {
if (e.keyCode == 13) {
// Do something
}
});
Another (worse) way is:
In case that your cursor is in the input and your key events arent working you should check every key which is pressed when the cursor is in the input. To do this you should add the change() function at your input and in the function you can check the keys that are pressed when the cursor is in the input
$( "your_input" ).change(function() {
var key_pressed = your_input.text().slice(-1);
if (key_pressed = "e" )
//do that
});

Related

Change variable from input field

I've been learning some jQuery and using w3schools. My intention is to allow the user to bind any key on their keyboard to the currently hardcoded key. I tried creating a variable and having that changed based on the input of the text field to change the keycode but haven't had any luck (Just like how you see in some games when they allow you to map a key to another). I was researching on w3schools and I believe I could use switch case, but I believe that would be too long and not tidy?
Here is what I have so far. (Alert doesn't seem to work here, going to the actual JSFiddle via the hyperlink works though)
$('input').bind("binding", function(e) {
alert("Backspace"); //Pop up to see
});
$('input').keyup(function(e) {
if (e.keyCode == 8) { // 8 = backspace
$(this).trigger("binding"); //will allow the message to be displayed
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try it here <input type="text"> Change the input <input class type="text">
Any suggestions are grateful. Thank you
You can try this for binding one key to backspace. It takes input from the first input element and the key pressed is then bounded to the backspace and only that key will function as a backspace key
$('#try').bind("binding", function(e) {
alert("Backspace"); //Pop up to see
});
var a;
$('#change').keyup(function(e) {
a = e.keyCode;
$(this).prop('disabled', true);
});
$('#try').keyup(function(e) {
if (e.keyCode == a) {
$(this).trigger("binding"); //will allow the message to be displayed
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Press the key you want to bind to backspace <input type="text" id="change"><br> Change the input <input id="try" type="text">
By default the binded key will be Backspace. You can change the key by typing something in the first input. It will take only one character.
Then when that key is input in the second input field the message will be triggered.
Explanation:
The keycode of the key entered in the first input is saved in the key_code variable and used later on in the other key_up event to check whether it matches
var key_code = 8
$('#changekey').keyup("input", function(e) {
key_code = e.keyCode;
});
$('input').on("binding", function(e) {
alert("Backspace"); //Pop up to see
});
$('#text').keyup(function(e) {
if (e.keyCode == key_code) //8 = backspace
{
$(this).trigger("binding"); //will allow the message to be displayed
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try it here <input type="text" id="changekey" maxlength = 1 > Change the input <input class type="text" id="text">

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="" />

Increase Number Value Displayed on Screen

I need to have a number that's displayed on a web page that will increase or decrease when the up or down arrow keys are pressed. I found/massaged together javascript file to do this but I can't seem to get it to work with my HTML. I was trying to link it to a html textbox but it would not work.
if someone could help me with the HTML to get this working that would be great.
var setTimeoutId;
var keyIs = "up";
function myIncrementFunction()
{
var num = parseFloat(myText.value)+1;
myText.value = num;
}
myText.onkeydown = function(e)
{
keyIs = "down";
if(keyIs == "down")
{
var e = e || event ;
if (e.keyCode == 38)
{
for(var s=0; s<1; s++)
setTimeoutId = setTimeout('myIncrementFunction()',100);
}
}
}
myText.onkeyup = function(e)
{
keyIs = "up";
}
Tried this and it still is not working.. > ?
number.html
<html>
<head>
<script type="text/javascript" src="number.js"></script>
</head>
<body>
<input type="text" id="myText" />
</body>
</html>
number.js
var myText = document.getElementById("myText");
// Capture keyDown events
myText.onkeydown = function(e) {
// "38" is the up arrow key
if (e.keyCode == 38) {
// increment the value in the text input
myText.value++;
// "40" is the down arrow key
} else if (e.keyCode == 40) {
// decrement the value in the text input
myText.value--;
}
}
I don't understand why it works in the example posted and when I save my files and open it in the browser it will not work!
I'm on OSX Lion using Chrome/Safari
It looks like there are a couple of things going on. First, as jayp points out in his comment, you aren't defining what myText is.
Secondly, I think you're over-complicating this a bit. How about trying something like this:
Give your text input an ID, something like <input type="text" id="myText" />
Then use something like this:
// Assign our text input to a variable
var myText = document.getElementById("myText");
// Capture keyDown events
myText.onkeydown = function(e) {
// "38" is the up arrow key
if (e.keyCode == 38) {
// increment the value in the text input
myText.value++;
// "40" is the down arrow key
} else if (e.keyCode == 40) {
// decrement the value in the text input
myText.value--;
}
}
This is a pretty simplified example, but should get you pointed in the right direction. Hope it helps.
See a working example at JSFiddle
Edit:
It's not working in your case because the script is trying to find the input element before the page is fully loaded. You can move your script to the bottom of the page like this:
<html>
<head></head>
<body>
<input type="text" id="myText" />
<script type="text/javascript" src="number.js"></script>
</body>
</html>
In your number.js, you are increasing the value of the text field, but you have no value originally set, therefore there is nothing to increase.
Try editing your HTML so that you have:
<input type="text" id="myText" value="" />
There's a small jQuery plugin for doing this: https://github.com/nakupanda/number-updown
Usages:
$('#textInput').updown();
View live demo here: http://jsfiddle.net/XCtaH/embedded/result/
Keyboard and mousewheel events supported

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>

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