Use Enter Keydown Event to move to the next Input - javascript

I have a large form. As users are filling in values I would like for the enter key to take on the same behavior as the tab key (i.e. I want to move the user to the next input element when the enter key is pressed.
Due to the way my HTML form is structured into various sections I cannot assume the next input is a sibling of the current input. Additionally, the classes and IDs of the inputs are not sequential.
jQuery:
$("input").bind("keydown", function (event) {
document.getElementById('keys').innerHTML = document.getElementById('keys').innerHTML + event.which + " ";
if (event.which === 13) {
event.stopPropagation();
event.preventDefault();
var e = $.Event("keydown");
e.which = 9;
$(this).trigger(e);
}
});
JSFIDDLE

This will do your job
$("input").not($(":button")).keypress(function (evt) {
if (evt.keyCode == 13) {
iname = $(this).val();
if (iname !== 'Submit') {
var fields = $(this).parents('form:eq(0),body').find('button, input, textarea, select');
var index = fields.index(this);
if (index > -1 && (index + 1) < fields.length) {
fields.eq(index + 1).focus();
}
return false;
}
}
});
example

Related

How to set enter key press for a HTML tag with Javascript

I would like to add an enter key press after the alert(get_approve_2.innerHTML); as the code below.
This means that every time the alert runs, the enter key press then starts after the alert's popup.
$(get_status1).change(function(){ // Get value of Status 1
//alert($('option:selected', $(this)).text());
var value = $('option:selected', $(this)).text();
var get_approve_2 = document.getElementById("ctl00_m_g_ee431d81_6c29_4b13_a29e_884f483a4e68_ff171_ctl00_ctl00_UserField_upLevelDiv");
if (value == "Approve"){
var name_approve_2 = "Receptionist";
get_approve_2.innerHTML = name_approve_2;
alert(get_approve_2.innerHTML);
// Enter key press goes here
}
else{
//alert("Reject");
get_approve_2.innerHTML = " ";
}
});
I have tried with this but I don't know how it can be run automatically or be trigged
function runScript(e) {
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
If you're using jQuery.You can use which event on key code 13 for the enter key
// Enter key press goes here
$('Your selector').on('keyup', function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
As you said if you want to automatically be trigged
function runScript(e) {
if (e.keyCode == 13) {
var tb = document.getElementById("scriptBox");
eval(tb.value);
return false;
}
}
Add your function there
if (value == "Approve"){
var name_approve_2 = "Receptionist";
get_approve_2.innerHTML = name_approve_2;
alert(get_approve_2.innerHTML);
// Enter key press goes here
runScript(13); //run your function there
}

How to stop the backspace for particular element in jquery or javascript?

I am new to javascript and I am making a web application. Basically its a simple memo using html5.
My html code:
<ul contenteditable="true">
<br/>abc<br/>
def<br/>
ghi<br/>
</ul>
and my javascript:
window.onkeydown = backspace;
function backspace() {
var key = event.keyCode || event.charCode;
var lis = document.getElementsByTagName("li");
for (var i = 0; i < lis.length; i++) {
var li = lis[i];
if (li.innerHTML == "<br>") {
if (!li.id) {
li.id = "ttt";
if (key == 8) {
return false;
}
}
}
}
return true;
}
I tried the basic backspace return false but the problem is if the li tag is empty the other li tags will not take the backspace event even if it has a character.
you can add event handler to document keypress
then check if backspace and the type of element you want 'LI'
$(document).keypress(function(e) {
var key = e.which;
if (key == 8 && e.target.attributes[0].value != "text") {
return false;
}
});
you can can replace text with the type of element you want
$('input').keydown(function(e){
if(e.keyCode == 8) {
e.preventDefault();
alert('we arent allowing deletes');
}
});
http://jsfiddle.net/dq8tr/3/

Focus button from javascript withour clicking it

I call
element.focus();
Where element is HTMLInputElement of type=button.
But then the browser clicks the button! That's in mozilla and chrome.
How do i highlight the button with selection, but not initiate the click event?
No .focus() doesn't click the button or submits the form: http://jsbin.com/onirac/1/edit
It does exactly what you want it to.
Well, i've identified the reason.
I was handling the onkeydown event for Enter key.
The solution is to use
e.preventDefault();
function ConvertEnterToTab(s, e, numSkipElements) {
var keyCode = e.keyCode || e.htmlEvent.keyCode;
if (keyCode === 13) {
var tabIndex = s.tabIndex || s.inputElement.tabIndex;
if (numSkipElements == undefined) {
numSkipElements = 0;
}
var nextElement = FindNextElementByTabIndex(tabIndex + numSkipElements);
if (nextElement != undefined) {
nextElement.focus();
return e.preventDefault ? e.preventDefault() : e.htmlEvent.preventDefault(); // this is the solution
}
}
}
function FindNextElementByTabIndex(currentTabIndex, maxTabIndex) {
if (maxTabIndex == undefined) {
maxTabIndex = 100;
}
var tempIndex = currentTabIndex + 1;
while (!$('[tabindex='+ tempIndex+ ']')[0] || tempIndex === maxTabIndex) {
tempIndex++;
}
return $('[tabindex=' + tempIndex + ']')[0];
}

How to simulate TAB on ENTER keypress in javascript or jQuery

I want to change keycode in keydown ( key press ) in all input in a page.I want to replace Enter keycode with TAB key code. How I can do this?
thanks
EDIT 1)
Consider this code:
<div>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:RadioButtonList>
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server">3333</asp:TextBox>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
</div>
I want when user press Enter on eny of above control focus go to next control.
thanks
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
});
Then enable the feature by adding plus-as-tab="true" to the form fields you want to use enter-as-tab in, or some other element that contains these form fields. Radio buttons should not be a problem, as they are covered by my other library, EmulateTab - see autonavigation of radio buttons in that demo.
<div plus-as-tab="true">
<!-- all focusable elements inside the <div> will be enabled -->
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<!-- Radio buttons should not be a problem. -->
</asp:RadioButtonList>
</div>
You can try it out yourself in the PlusAsTab enter as tab demo.
This code is to replace enter with tab character:
$("#wmd-input").bind("keypress", function(e) {
if (e.keyCode == 13) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\t");
}, 1);
}
});
Live Demo
UPDATE:
This code is to focus to on the next element:
$(document).ready(function () {
$("input,select").bind("keydown", function (e) {
if (e.keyCode == 13) {
var allInputs = $("input,select");
for (var i = 0; i < allInputs.length; i++) {
if (allInputs[i] == this) {
while ((allInputs[i]).name == (allInputs[i + 1]).name) {
i++;
}
if ((i + 1) < allInputs.length) $(allInputs[i + 1]).focus();
}
}
}
});
});
Hope this works
$('input,textarea').keydown(function(){
if(event.keyCode==13) {
event.keyCode = 9;
}
});
Edit
Try this http://jsfiddle.net/GUmUg/. Play around with selectors to make this work as i don't know asp
$('input,textarea').keypress(function(e){
if(e.keyCode==13) {
$(this).next().focus();
}
});
$('input').on('keydown',function(e){
var keyCode = e.keyCode || e.which;
if(e.keyCode === 13) {
e.preventDefault();
$('input')[$('input').index(this)+1].focus();
}
});
check fiddle here : http://jsfiddle.net/Pd5QC/
The way I do it is by using jquery to each over your selection and focusing on the element after the current on you are on.
$(document).on('keyup', '.my-input', function (ev) {
if (ev.keyCode == '13') {
var currentInput = this;
var isOnCurrent = false;
$('.my-input').each(function () {
if (isOnCurrent == true) {
$(this).focus();
return false;
}
if (this == currentInput) {
isOnCurrent = true;
}
});
}
});
I think this work:
$('input').live("keypress", function (e) {
/* ENTER PRESSED*/
var OffSet = 0;
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
if ($(this).is("input[type='radio']")) {
var tblID = $(this).closest('table').attr('id');
var radios = $('#' + tblID).find(":input");
//alert(radios.index(this));
OffSet = radios.length - radios.index(this) - 1;
}
//alert(OffSet);
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
inputs[idx + OffSet].blur();
try {
inputs[idx + OffSet].selectionStart = inputs[idx + OffSet].selectionEnd = -1;
} catch (e) {
}
if (idx == inputs.length - 1) {
inputs[0].select();
} else {
inputs[idx + 1 + OffSet].focus(); // handles submit buttons
try {
inputs[idx + 1 + OffSet].select();
} catch (e) {
}
}
return false;
}
});
I created a simple jQuery plugin which does solve this problem. It uses the ':tabbable' selector of jQuery UI to find the next 'tabbable' element and selects it.
Example usage:
// Simulate tab key when enter is pressed
$('.myElement').bind('keypress', function(event){
if(event.which === 13){
if(event.shiftKey){
$.tabPrev();
}
else{
$.tabNext();
}
return false;
}
});
$(document).ready(function() {
//Objetos con CssClass="EntTab" sustituye el Enter (keycode 13) por un Tabulador (keycode 9)!!
$(".EntTab").bind("keypress", function(e) {
if (e.keyCode == 13) {
var inps = $("input, select"); //add select too
for (var x = 0; x < inps.length; x++) {
if (inps[x] == this) {
while ((inps[x]).name == (inps[x + 1]).name) {
x++;
}
if ((x + 1) < inps.length) $(inps[x + 1]).focus();
}
} e.preventDefault();
}
});
});

Calling click from keydown, but getting the correct checkbox checked property

This isn't a jQuery only question as it has to do with events and order of operation. Consider the following code, which is based on jQuery multiSelect plugin (please post citation if you can find it):
Fiddle with it here
var debug = $('#debug');
var updateLog = function (msg){
debug.prepend(msg + '\n');
};
var title = $('#title').focus();
var container = $('#container');
title.keydown(function(e){
// up or down arrows
if (e.keyCode == 40 || e.keyCode == 38) {
var labels = container.find('label');
var idx_old = labels.index(labels.filter('.hover'));
var idx_new = -1;
if (idx_old < 0) {
container.find('label:first').addClass('hover');
} else if (e.keyCode == 40 && idx_old < labels.length - 1) {
idx_new = idx_old + 1;
} else if (e.keyCode == 38 && idx_old > 0) {
idx_new = idx_old - 1;
}
if (idx_new >= 0) {
jQuery(labels.get(idx_old)).removeClass('hover');
jQuery(labels.get(idx_new)).addClass('hover');
}
return false;
}
// space/return buttons
if (e.keyCode == 13 || e.keyCode == 32) {
var input_obj = container.find('label.hover input:checkbox');
input_obj.click();
return false;
}
});
// When the input is triggered with mouse
container
.find('input:checkbox')
.click(function(){
var cb = $(this);
var class = "checked";
if (cb.prop(class)){
cb.parent('label').addClass(class);
} else {
cb.parent('label').removeClass(class);
}
updateLog( cb.closest('label').text().split(/[\s\n]+/).join(' ') + ': '
+ this.checked + ' , '
+ cb.prop(class));
title.focus();
})
;
Notice the difference in the checkbox value for when you click directly on the checkbox, versus when you select the checkbox with the space/enter key. I believe this is because it's calling click during the keydown event, so the value of the checkbox is not yet changed; whereas if you actually click the input, the mouseup event occurs before the click (?), so the setting is applied.
The multiselect plugin does not call the click event, it has almost duplicate code. I'm curious if it would be better to pass a parameter to the click event (or use a global) to detect if it issued by the keyboard or mouse, or if it is better to just do what the plugin did and have the code inside the keydown function.
Obviously, if the log were after the click() runs, the keydown would return trues, but there are things that happen inside of click that are based on the input's checked status.
Changed it to use the change event instead of the click event for the checkboxes
http://jsfiddle.net/QJsPc/4/

Categories