Selenium testing - events seem not to be fired - javascript

I'm using embedded glassfish to deploy my web application and test it with arquillian remote control. While everything's been going nice so far, we found a problem when trying to deal with a suggestions feature in the application. It basically consists of a text box which offers a list of possibly matching items once 3 or more characters have been typed.
<div class="uiModuleSelectingConcepts suggestion_${cc.id}">
<div class="searchBox">
<fieldset>
<input type="text"
class="sample"
value="${cc.attrs.input_label}"
placeholder="${cc.attrs.input_label}"/>
<i></i>
</fieldset>
</div>
<a4j:outputPanel id="suggestion_component_container"
styleClass="suggestionsWrapper"
layout="block">
<div class="suggestionsList_${cc.id}">
</div>
</a4j:outputPanel>
</div>
Some events are added so these suggestions are properly displayed, as follows (in the following code, the parameter inputNode) is the textbox itself where the user types...there is where we add the events):
this.addEventHandlers = function (inputNode, suggestionCallback, params) {
var parent = this;
inputNode
/*
* keypress event.
*/
.keypress(function(event) {
if (event.keyCode === 13) {
event.preventDefault();
}
})
/*
* keyup event.
*/
.keyup(function(event) {
switch (event.keyCode) {
/**
* Up arrow.
*/
case 38:
event.stopPropagation();
event.preventDefault();
var suggestionsWrapper = parent._params.list;
var currentSelectedValue = null;
if (suggestionsWrapper.find(".suggestionItem").length) {
if (suggestionsWrapper.find(".suggestionItem:first").hasClass("focused")) {
suggestionsWrapper.find(".focused").removeClass("focused");
suggestionsWrapper.find(".suggestionItem:last").addClass("focused");
//currentSelectedValue = suggestionsWrapper.find(".suggestionItem:last").val();
} else {
suggestionsWrapper.find(".focused").removeClass("focused").prev().addClass("focused");
};
//set the selected value to input.
//console.debug("Current Valiue", suggestionsWrapper.find(".focused"));
var e = suggestionsWrapper.find(".focused");
if (e.length > 0) {
//console.debug("Current e", e);
currentSelectedValue = typeof e === 'undefined' ? null : e.attr('data-suggest');
//console.debug("Current Valiue", currentSelectedValue);
if (currentSelectedValue != null) {
jQuery(this).val(Encoder.htmlDecode(currentSelectedValue));
}
}
}
parent._blur = false;
break;
/**
* Down arrow.
*/
case 40:
var suggestionsWrapper = parent._params.list;
var currentSelectedValue = null;
if (suggestionsWrapper.find(".suggestionItem").length) {
if (suggestionsWrapper.find(
".suggestionItem:last").hasClass("focused")) {
suggestionsWrapper.find(".focused").removeClass("focused");
suggestionsWrapper.find(".suggestionItem:first").addClass("focused");
} else {
suggestionsWrapper.find(".focused").removeClass("focused").next().addClass("focused");
};
//console.debug("Current Valiue", suggestionsWrapper.find(".focused"));
var e = suggestionsWrapper.find(".focused");
//console.debug("Current e", e);
if (e.length > 0) {
currentSelectedValue = typeof e === 'undefined' ? null : e.attr('data-suggest');
//console.debug("Current Valiue", currentSelectedValue);
if (currentSelectedValue != null) {
jQuery(this).val(Encoder.htmlDecode(currentSelectedValue));
}
}
}
parent._blur = false;
break;
/**
* ENTER key
*/
case 13:
event.stopPropagation();
event.preventDefault();
var suggestionsWrapper = parent._params.list;
var oConcept = suggestionsWrapper.find(".focused");
if (typeof oConcept !== "undefined") {
oConcept.trigger("click");
}
parent._blur = true;
parent._cleanSuggestions();
jQuery(this).blur();
break;
/**
* ESC key event.
*/
case 27:
event.stopPropagation();
event.preventDefault();
var sValue = jQuery(this).attr("data-default");
sValue = jQuery.trim(sValue);
if (sValue === jQuery(this).attr("data-default")) {
jQuery(this).addClass("sample").blur();
}
parent._blur = true;
parent._cleanSuggestions();
jQuery(this).val("");
jQuery(this).blur();
break;
default:
var suggestionsWrapper = parent._params.list;
//var typeRight = jQuery(this).parents(".tabContent").attr("id");
var sValue = jQuery.trim(jQuery(this).val());
//var oThisInput = jQuery(this);
if (sValue.length > MEDIA.configuration.SUGGESTION_LIMIT) {
suggestionsWrapper.find(".suggestionItem").remove();
global.uiDelay( function() {
parent.displayLoading();
suggestionCallback(sValue, MEDIA.util.getTrueFalseValue(parent._params.retrieveOnlyClasses) ? suggestOnlyConcepts : "");
}, 1000);
} else {
parent.writeMore();
}
parent._blur = true;
break;
};
}).keydown(function(event) {
switch (event.keyCode) {
case 38: // up
event.stopPropagation();
event.preventDefault();
break;
case 40: // down
event.stopPropagation();
event.preventDefault();
break;
default:
break;
};
}).focus(function() {
jQuery(this).val("");
parent._blur = true;
// when suggestions lose focus
}).blur(function() {
if (parent._blur) {
jQuery(this).val("");
parent._cleanSuggestions();
}
});
};
When the application is deployed normally (for no testing purposes, without selenium) it works as expected and when typing something the suggestions are displayed. However, when using Selenium no matter what is typed in the box nothing happens. We've tried many possibilities and combinations with .keyDown(), .keyPress(), .keyUp() with their char, keyCode and native variants. Also, .type(), .typeKeys()....all of them to no avail. It would seem as though for some reasons the events are ignored (the funny thing is, if we hand-type some text in the browser selenium opens for testing the application, the suggestions -do- display. They only don't when it's selenium doing the typing).
Any help would be greatly appreciated. Not sure if I made complete sense, we'd be happy to clarify.
Greetings.

I used this simple testpage and jQuery 1.7.2 (the input to the first field should get copied into the another):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
</head>
<body>
<input type="text" id="myInput" />
<input type="text" id="yourInput" />
<script>
$("#myInput").keyup(function(event) {
$("#yourInput").val(this.value);
});
</script>
</body>
</html>
Let me state the annoying truth right in the beginning: With WebDriver, everything works well and smoothly.
WebDriver driver = new InternetExplorerDriver();
driver.get("the path to the file");
driver.findElement(By.id("myInput")).sendKeys("Hello.");
driver.quit();
Anyway, what I was able to make it work in Selenium RC, too:
sele.focus("id=myInput");
sele.keyPressNative(String.valueOf(KeyEvent.VK_H));
sele.keyPressNative(String.valueOf(KeyEvent.VK_E));
sele.keyPressNative(String.valueOf(KeyEvent.VK_L));
sele.keyPressNative(String.valueOf(KeyEvent.VK_L));
sele.keyPressNative(String.valueOf(KeyEvent.VK_O));
It kind of sucks, but it's the best I came up with where the event works.

Related

Using backpressure for keystroke in RxJs

I'm trying to capture the user keystroke using RxJS, and for each stroke, generate a result object which contains the key, the duration of the stroke (time between keyup and keydown events), and the interval between previous strokes (using timeInterval).
See the image bellow for an overview.
So far, my code is working : Hello outputs ShiftLeftHELLO.
But when I writing faster (as usual I mean), everything breaks up and World outputs ShiftLeftShiftLeftOLD.
Do you have any suggestion on implementing backpressure, buffering or something else in my code to prevent this behavior ?
(function (document) {
var textarea = document.querySelector("#input");
var keyUpStream = Rx.DOM.keyup(textarea);
var keyDownStream = Rx.DOM.keydown(textarea);
var keyStrokeStream = Rx.Observable.merge(keyDownStream, keyUpStream);
var keystroke = keyStrokeStream.filter((function() {
var keysPressed = {};
return function(e) {
var k = e.which;
if (e.type == 'keyup') {
delete keysPressed[k];
return true;
} else if (e.type == 'keydown') {
if (keysPressed[k]) {
return false;
} else {
keysPressed[k] = true;
return true;
}
}
};
})())
.distinctUntilChanged(function (e){
return e.type + e.which;
})
.timeInterval()
.bufferWithCount(2)
.zip(function (evts){
return {
"ts" : Date.now(),
"key": evts[0].value.code,
"evts" : evts,
"duration" : evts.reduce(function(a, b){
return b.value.timeStamp - a.value.timeStamp;
})
};
}).subscribe(function (e){
console.log(e);
document.querySelector("#output").textContent += e.key.replace("Key", '');
document.querySelector("#console").textContent += JSON.stringify(e);
});
})(document);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs-dom/7.0.3/rx.dom.js"></script>
<h1>KeyStroke</h1>
<textarea id="input" rows="5" cols="50"></textarea>
<div id="output"></div>
<div id="console"></div>
Disclaimer: Rxjs noob here.
The problem is that your code expect a keyup from a key after a keydown from that same key. When you type fast, you have a race condition on keystrokes, resulting in a buffer with several keydowns or keyups. Not what you expect in your buffer.
I've modified the code to take advantage of your filter function. That function returns only keyup events and it saves the corresponding keydown stroke. This way, you calculate the interval within the filter function. I'm pretty sure that there's a more elegant solution using only RxJS functions but since you already used state in the filter function, I've modified it a little.
The snippet now shows a proper output. I think it solves your problem but it's not a good way of using RxJS (as I said we're storing state in the filter function).
(function (document) {
var textarea = document.querySelector("#input");
var keyUpStream = Rx.DOM.keyup(textarea);
var keyDownStream = Rx.DOM.keydown(textarea);
var keyStrokeStream = Rx.Observable.merge(keyDownStream, keyUpStream);
var keystroke = keyStrokeStream.filter((function() {
var keysPressed = {};
return function(e) {
var key = e.which;
var result;
if (e.type == 'keyup' && keysPressed.hasOwnProperty(key)) {
e.strokeInterval = Date.now() - keysPressed[key];
delete keysPressed[key];
return true;
} else if (e.type == 'keydown') {
if (!keysPressed.hasOwnProperty(key)) {
keysPressed[key] = Date.now();
}
return false;
}
return false;
};
})())
.map(function (evt){
return {
"ts" : Date.now(),
"key": evt.code,
"duration" : evt.strokeInterval
};
})
.subscribe(function (e){
console.log(e);
document.querySelector("#output").textContent += e.key.replace("Key", '');
document.querySelector("#console").textContent += JSON.stringify(e);
});
})(document);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs-dom/7.0.3/rx.dom.js"></script>
<h1>KeyStroke</h1>
<textarea id="input" rows="5" cols="50"></textarea>
<div id="output"></div>
<div id="console"></div>

tabindex issue with select2

I am having an issue with the taborder on my form whilst using select2.
I have an input form that I want the user to be able to tab through in order.
I have been able to order the text input fields but not select2 dropdownlists.
It appears the issue is with them having a default tabindex="-1", as below;
> <div id="s2id_ctl00_MainContent_ddlAreaKept" class="select2-container
> form-control">
> <a class="select2-choice" tabindex="-1" onclick="return false;" href="javascript:void(0)">
> <input id="s2id_autogen4" class="select2-focusser select2-offscreen" type="text" tabindex="0">
> <div class="select2-drop select2-display-none select2-with-searchbox">
> </div>
> <select id="ctl00_MainContent_ddlAreaKept" class="form-control select2-offscreen" name="ctl00$MainContent$ddlAreaKept" tabindex="-1">
I have also written the following javascript to add tabIndex values to the fields but it isn't working how I'd like.
var tabOrder = 0;
document.getElementById("ctl00_MainContent_ddlAreaKept").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_ddlNCDYears").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtVehicleValue").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtAge").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtForename").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtSurname").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtEmail").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_txtPhoneNumber").tabIndex = tabOrder++;
document.getElementById("ctl00_MainContent_btnGetQuote").tabIndex = tabOrder++;
The dropdownlists don't get tabbed into, it skips them and goes through the textboxes as it should.
Any help much appreciated!
SOLVED : I tried:
var tabOrder = 1;
and this has solved the issue. I don't exactly know why or how :|
There is a solution in github, you can create a js file and then you include it under the call of select2, inside this new file you must paste this:
jQuery(document).ready(function($) {
var docBody = $(document.body);
var shiftPressed = false;
var clickedOutside = false;
//var keyPressed = 0;
docBody.on('keydown', function(e) {
var keyCaptured = (e.keyCode ? e.keyCode : e.which);
//shiftPressed = keyCaptured == 16 ? true : false;
if (keyCaptured == 16) { shiftPressed = true; }
});
docBody.on('keyup', function(e) {
var keyCaptured = (e.keyCode ? e.keyCode : e.which);
//shiftPressed = keyCaptured == 16 ? true : false;
if (keyCaptured == 16) { shiftPressed = false; }
});
docBody.on('mousedown', function(e){
// remove other focused references
clickedOutside = false;
// record focus
if ($(e.target).is('[class*="select2"]')!=true) {
clickedOutside = true;
}
});
docBody.on('select2:opening', function(e) {
// this element has focus, remove other flags
clickedOutside = false;
// flag this Select2 as open
$(e.target).attr('data-s2open', 1);
});
docBody.on('select2:closing', function(e) {
// remove flag as Select2 is now closed
$(e.target).removeAttr('data-s2open');
});
docBody.on('select2:close', function(e) {
var elSelect = $(e.target);
elSelect.removeAttr('data-s2open');
var currentForm = elSelect.closest('form');
var othersOpen = currentForm.has('[data-s2open]').length;
if (othersOpen == 0 && clickedOutside==false) {
/* Find all inputs on the current form that would normally not be focus`able:
* - includes hidden <select> elements whose parents are visible (Select2)
* - EXCLUDES hidden <input>, hidden <button>, and hidden <textarea> elements
* - EXCLUDES disabled inputs
* - EXCLUDES read-only inputs
*/
var inputs = currentForm.find(':input:enabled:not([readonly], input:hidden, button:hidden, textarea:hidden)')
.not(function () { // do not include inputs with hidden parents
return $(this).parent().is(':hidden');
});
var elFocus = null;
$.each(inputs, function (index) {
var elInput = $(this);
if (elInput.attr('id') == elSelect.attr('id')) {
if ( shiftPressed) { // Shift+Tab
elFocus = inputs.eq(index - 1);
} else {
elFocus = inputs.eq(index + 1);
}
return false;
}
});
if (elFocus !== null) {
// automatically move focus to the next field on the form
var isSelect2 = elFocus.siblings('.select2').length > 0;
if (isSelect2) {
elFocus.select2('open');
} else {
elFocus.focus();
}
}
}
});
docBody.on('focus', '.select2', function(e) {
var elSelect = $(this).siblings('select');
if (elSelect.is('[disabled]')==false && elSelect.is('[data-s2open]')==false
&& $(this).has('.select2-selection--single').length>0) {
elSelect.attr('data-s2open', 1);
elSelect.select2('open');
}
});
});
This work for me, if you want to know more: https://github.com/peledies/select2-tab-fix
© 2017 GitHub, Inc.
Terms
Privacy
Security
Status
Help
Contact GitHub
API
Training
Shop
Blog
About
focus it after select it!
$('.select2').on('select2:select', function (e) {
$(this).focus();
});
for your code replace .select2-offscreen with my .select2.
S F My English!
You could bind load event and trigger it on first time loaded
As you can see , the tabindex of the select control will become "3" instead of "-1"
$(document).ready(function() {
var $select2 = $("#tab2");
$select2.data('placeholder', 'Please Chhose').select2({
formatNoMatches: function (term) {
return 'No Match "' + term + '" Item';
},
allowClear: true
}).on("load", function(e) {
$(this).prop('tabindex',3);
}).trigger('load');
$("#tab1").prop('tabindex',4);
$("#tab3").prop('tabindex',2);
$("#tab4").prop('tabindex',1);
}
JSBIN
This code worked for me. I focus the first element in the modal:
$('#modalId').on('shown.bs.modal', function () {
$('#FirstElement').focus()
});
TabIndex Issue might happen after the form reset.
As per the documentation You may clear all current selections in a Select2 control by setting the value of the control to null:
$(selector).val(null).trigger("change");

JavaScript force an OnChange in Maximo

I'm currently working on a Bookmarklet for Maximo, which is a Java EE application, and I need to populate a few input boxes.
Generally when a use inputs data into the box they click a button that gives them a popup and they search for the value to be added to the script. Or they can type the name and hit tab/enter and it turns it to capital letters and does a few things in the background (not sure what it does exactly).
I currently use
Javascript: $('mx1354').value = "KHBRARR"; $('mx1354').ov= "KHBRARR";
But it does not work like I need it to. It set's the input box to the value needed, but it doesn't run the background functions so when I hit the save button it doesn't recognize it as any changes and discards what I put into the box.
How could I simulate a tab/enter button has been pressed?
So far I've tried to call the onchange, focus/blur, and click functions (Not 100% sure if I called them correctly).
The dojo library is part of the application, so I'm not sure if I can use one if it's feature or if jQuery would cause a conflict.
P.S. This needs to run in IE.
The OnChange Function:
function tb_(event)
{
event = (event) ? event : ((window.event) ? window.event : "");
if(DESIGNMODE)
return;
var ro = this.readOnly;
var exc=(this.getAttribute("exc")=="1");
switch(event.type)
{
case "mousedown":
if(getFocusId()==this.id)
this.setAttribute("stoptcclick","true");
break;
case "mouseup":
if (isIE() && !hasFocus(this))
{
this.focus();
}
if (isBidiEnabled)
{
adjustCaret(event, this); // bidi-hcg-AS
}
break;
case "blur":
input_onblur(event,this);
if (isBidiEnabled) // bidi-hcg-SC
input_bidi_onblur(event, this);
break;
case "change":
if(!ro)
input_changed(event,this);
break;
case "click":
if(overError(event,this))
showFieldError(event,this,true);
var liclick=this.getAttribute("liclick");
var li=this.getAttribute("li");
if(li!="" && liclick=="1")
{
frontEndEvent(getElement(li),'click');
}
if(this.getAttribute("stoptcclick")=="true")
{
event.cancelBubble=true;
}
this.setAttribute("stoptcclick","false");
break;
case "focus":
input_onfocus(event,this);
if (isBidiEnabled) // bidi-hcg-SC
input_bidi_onfocus(event, this);
this.select();
break;
case "keydown":
this.setAttribute("keydown","true");
if(!ro)
{
if(isBidiEnabled)
processBackspaceDelete(event,this); // bidi-hcg-AS
if(hasKeyCode(event, 'KEYCODE_DELETE') || hasKeyCode(event, 'KEYCODE_BACKSPACE'))
{
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
}
if((hasKeyCode(event, 'KEYCODE_TAB') || hasKeyCode(event, 'KEYCODE_ESC')))
{
var taMatch = dojo.attr(this, "ta_match");
if(taMatch) {
if(taMatch.toLowerCase().indexOf(this.value.toLowerCase()) == 0)
{
console.log("tamatch="+taMatch);
this.value = taMatch;
input_keydown(event, this);
dojo.attr(this, {"prekeyvalue" : ""});
input_forceChanged(this);
inputchanged = false;
return; // don't want to do input_keydown again so preKeyValue will work
}
}
if(this.getAttribute("PopupType"))
{
var popup = dijit.byId(dojohelper.getPopupId(this));
if (popup)
{
dojohelper.closePickerPopup(popup);
if(hasKeyCode(event, 'KEYCODE_ESC'))
{
if (event.preventDefault)
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
return;
}
}
}
}
input_keydown(event,this);
datespin(event,this);
}
else if(hasKeyCode(event,'KEYCODE_ENTER') || (hasKeyCode(event,'KEYCODE_DOWN_ARROW') && this.getAttribute("liclick")))
{
var lbId = this.getAttribute("li");
frontEndEvent(getElement(lbId), 'click');
}
else if(hasKeyCode(event,KEYCODE_BACKSPACE))
{
event.cancelBubble=true;
event.returnValue=false;
}
break;
case "keypress":
if(!ro)
{
if(event.ctrlKey==false && hasKeyCode(event,'KEYCODE_ENTER'))
{
var db = this.getAttribute("db");
if(db!="")
{
sendClick(db);
}
}
}
break;
case "keyup":
var keyDown = this.getAttribute("keydown");
this.setAttribute("keydown","false");
if(event.ctrlKey && hasKeyCode(event,'KEYCODE_SPACEBAR'))
{
if(showFieldError(event,this,true))
{
return;
}
else
{
menus.typeAhead(this,0);
}
}
if(!ro)
{
if(isBidiEnabled)
processBidiKeys(event,this); // bidi-hcg-AS
numericcheck(event,this);
var min = this.getAttribute("min");
var max = this.getAttribute("max");
if(min && max && min!="NONE" || max!="NONE")
{
if(min!="NONE" && parseInt(this.value)<parseInt(min))
{
this.value=min;
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
this.select();
return false;
}
if(max!="NONE" && parseInt(this.value)>parseInt(max))
{
this.value=max;
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
this.select();
return false;
}
}
var defaultButton = false;
if(event.ctrlKey==false && hasKeyCode(event,'KEYCODE_ENTER'))
{
var db = this.getAttribute("db");
if(db!="")
{
defaultButton=true;
}
}
input_changed(event,this);
}
else
{
setFocusId(event,this);
}
if(showFieldHelp(event, this))
{
return;
}
if(keyDown=="true" && hasKeyCode(event, 'KEYCODE_ENTER') && !event.ctrlKey && !event.altKey)
{
menus.typeAhead(this,0);
return;
}
if(!hasKeyCode(event, 'KEYCODE_ENTER|KEYCODE_SHIFT|KEYCODE_CTRL|KEYCODE_ESC|KEYCODE_ALT|KEYCODE_TAB|KEYCODE_END|KEYCODE_HOME|KEYCODE_RIGHT_ARROW|KEYCODE_LEFT_ARROW')
&& !event.ctrlKey && !event.altKey)
{
menus.typeAhead(this,0);
}
break;
case "mousemove":
overError(event,this);
break;
case "cut":
case "paste":
if(!ro)
{
var fldInfo = this.getAttribute("fldInfo");
if(fldInfo)
{
fldInfo = dojo.fromJson(fldInfo);
if(!fldInfo.query || fldInfo.query!=true)
{
setButtonEnabled(saveButton,true);
}
}
window.setTimeout("inputchanged=true;input_forceChanged(dojo.byId('"+this.id+"'));", 20);
}
break;
}
}
After some time I found that in order to make a change to the page via JavaScript you need to submit a hidden form so it can verify on the back-end.
Here is the code I used to change the value of Input fields.
cc : function(e,v){
e.focus(); //Get focus of the element
e.value = v; //Change the value
e.onchange(); //Call the onchange event
e.blur(); //Unfocus the element
console.log("TITLE === "+e.title);
if(e.title.indexOf(v) != -1) {
return true; //The value partially matches the requested value. No need to update
} else {
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = e.id;
inputs.namedItem("changedcomponentvalue").value = v;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
}
//Value isn't set to the required value so pass false
return false;
}
run this
input_changed(null,document.getElementById('IDHERE'));
In maximo 7.5 i built a custom lookup
when i click the colored hyperlink java script is called to update the values back to parent form values or updated but on save the value or not updated
function riskmatrix_setvalue(callerId, lookupId, value,bgrColor,targetid){
if (document.getElementById(callerId).readOnly){
sendEvent('selectrecord', lookupId);
return;
}
textBoxCaller = document.getElementById(callerId);
//dojo.byId(callerId).setAttribute("value", value);
//dojo.byId(callerId).setAttribute("changed", true);
//dojohelper.input_changed_value(dojo.byId(callerId),value);
//textBoxCaller.style.background = bgrColor;
//var hiddenForm = getHiddenForm();
//if(!hiddenForm)
// return;
//var inputs = hiddenForm.elements;
//inputs.namedItem("event").value = "setvalue";
//inputs.namedItem("targetid").value = dojo.byId(callerId).id;
//inputs.namedItem("value").value = value;
//sendXHRFromHiddenForm();
textBoxCaller.focus(); //Get focus of the element
textBoxCaller.value = value; //Change the value
textBoxCaller.onchange(); //Call the onchange event
textBoxCaller.blur(); //Unfocus the element
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = textBoxCaller.id;
inputs.namedItem("changedcomponentvalue").value = value;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
sendEvent("dialogclose",lookupId);
}
Description
I changed a bit #Steven10172's perfect solution and made it into a Javascript re-usable function.
Made this into a separate answer since my edits to the original answer where i added this were refused :)
I also had to change the line e.onchange() to e.onchange(e) because otherwise the textbox handler (tb_(eventOrComponent) function) would throw TypeError: textbox.getAttribute is not a function.
Code
var setFakeValue = function(e,v){
console.log("Changing value for element:", e, "\nNew value:", v);
e.focus(); //Get focus of the element
e.value = v; //Change the value
e.onchange(e); //Call the onchange event
e.blur(); //Unfocus the element
if(e.title.indexOf(v) != -1) {
return true; //The value partially matches the requested value. No need to update
}
else {
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = e.id;
inputs.namedItem("changedcomponentvalue").value = v;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
}
//Value isn't set to the required value so pass false
return false;
}
Usage
setFakeValue(html_element, new_value);
Fun fact
I spent a lot of time searching for a solution to programmatically change an <input> value in Maximo... At some point i got really frustrated, gave up and started to think it just wasn't possible...
Some time ago i tried to search with no expectations at all and after some time i found the solution... Here...
Now... As you can see this is literally just a total copy of StackOverflow, including questions and solutions (marking the upvotes with plain text lol), but in Chinese... This got me curious and after a little search i found this post on StackOverflow..
High five to Chrome built-in webpage translator that let understand something on that page ^^

JavaScript key listener disabled when inside a text form

I have a key listener assigned to the arrow keys to navigate a slideshow. But I want to disable the key listener, temporarily, while a user is typing inside an input field. How can I do that? My current code looks like this:
//Listen to the keys
function checkKey(e) {
switch (e.keyCode) {
case 37:
changeImage('prev');
break;
case 39:
changeImage('next');;
break;
}
}
if (jQuery.browser.mozilla) {
jQuery(document).keypress (checkKey);
} else {
jQuery(document).keydown (checkKey);
}
First, there's no need for the browser check. For checking arrow keys, just use the keydown event for all keys.
Second, I suggest (as Sean Hogan did) checking the target of the event before doing the slideshow stuff. The following will work on all mainstream desktop browsers:
document.body.onkeydown = function(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
var targetTagName = (target.nodeType == 1) ? target.nodeName.toUpperCase() : "";
if ( !/INPUT|SELECT|TEXTAREA/.test(targetTagName) ) {
switch (evt.keyCode) {
case 37:
changeImage('prev');
break;
case 39:
changeImage('next');
break;
}
}
}
A bit ugly, but should work:
var moz = jQuery.browser.mozilla;
if (moz) {
jQuery(document).keypress(checkKey);
} else {
jQuery(document).keydown(checkKey);
}
jQuery("#myInput").focus(function() {
if (moz) {
jQuery(document).unbind("keypress");
} else {
jQuery(document).unbind("keydown");
}
}).blur(function() {
if (moz) {
jQuery(document).keypress(checkKey);
} else {
jQuery(document).keydown(checkKey);
}
});
If the focus is on an input element then that element will be the target for key events.
So you could just do a check on event.target.tagName.
e.g.
function checkKey(e) {
switch (e.target.tagName) {
case "INPUT": case "SELECT": case "TEXTAREA": return;
}
// rest of your handler goes here ...
}
Add onfocus and onblur event to the input field and set a global variable value. Check for that global variable in the begining of your checkKey event handler.
<input type="textbox" onfocus="window.inTextBox = true;" onblur="window.inTextBox = false;" />
function checkKey(e) {
if (!window.inTextBox)
{
...
}
}
I really like the simplicity of Ilya Volodin's suggestion, but I would set the event handler in the script and not embed it into the html:
var textFocus = false;
$("textbox").focus(function() {
textFocus = true;
});
$("textbox").blur(function() {
textFocus = false;
});
function navKeys() {
if (textFocus) {
return false;
} else {
......
}
}
This would be even simpler if jquery had :focus as a selector.
function navKeys() {
if ($("textbox:focus") {
return false;
} else {
......
}
}
But that is just hypothetical code at this point.

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