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();
}
});
});
Related
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
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/
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];
}
Normally when a user is visiting a web page and pressing TAB button on a keyboard, the selection moves from one element to another starting from the begining of the page.
I am looking for a solution to switch between two particular text areas by pressing TAB button on a keyboard with an initial focus on the first one when web page is loaded? All other elements on the page have to be ignored for this TAB key press event.
How can I achive this?
Thanx for your help!
= Update =
I have managed to make it work under Firefox 12.0 . IE and Chrome do not work properly. Asuming the text area IDs are #ICCID and #MSISDN, the Jquery looks like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$("#ICCID").focus();
});
var $inp = $('.cls');
$inp.bind('keydown', function(e) {
var key = e.which;
if (key == 9) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(".cls:eq(" + nxtIdx + ")").focus();
//Simulate Enter after TAB
var textInput = $("#MSISDN").val();
var lines = textInput .split(/\r|\r\n|\n/);
if (lines > 1) {
$("#MSISDN").on("keypress", function(e) {
if (e.keyCode == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\n");
}, 1);
}
});
}
}
if (key == 9) {
e.preventDefault();
var nxtIdx = $inp.index(this) - 1;
$(".cls:eq(" + nxtIdx + ")").focus();
//Simulate Enter after TAB
$("#ICCID").on("keypress", function(e) {
if (e.keyCode == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\n");
}, 1);
}
});
}
});
});
</script>
Catch the keydown action using jQuery, determine which textarea has focus, and then use the focus() method to set the focus to the other textarea.
Supposing that your textareas have id="textarea1" and id="textarea2". First you can set focus to the first textarea when the page loads by doing : $('#textarea1').focus();
$("body").keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
switch(code)
{
case 9:
if($("#textarea1").focus()){
//First one has focus, change to second one
$("#textarea2").focus();
}
else if($("#textarea2").focus()) {
//Second one has focus, change to first one
$("#textarea1").focus();
}
}
});
Ok I have found the solution for for my task! It also includes the simulation of ENTER key just after the TAB key event, so user do not need to hit ENTER to go to the new line. Tested with IE9, FF12, Chrome 18.0.x
Here it is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- Switching between ICCIDs and MSISDNs textareas + simulating ENTER key pressing after the TAB key event - START -->
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$("#ICCID").focus();
});
var $inp = $('.cls');
$inp.bind('keydown', function(e) {
var key = e.which;
if (key == 9) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(".cls:eq(" + nxtIdx + ")").focus();
//Simulate Enter after TAB
var textInput = $("#MSISDN").val();
var lines = textInput .split(/\r|\r\n|\n/);
if (lines > 1) {
$("#MSISDN").on("keyup", function(e) {
if (e.keyCode == 9 || e.which == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\r\n");
}, 1);
}
});
}
}
if (key == 9) {
e.preventDefault();
var nxtIdx = $inp.index(this) - 1;
$(".cls:eq(" + nxtIdx + ")").focus();
//Simulate Enter after TAB
$("#ICCID").on("keyup", function(e) {
if (e.keyCode == 9 || e.which == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\r\n");
}, 1);
}
});
}
});
});
</script>
<!-- Switching between ICCIDs and MSISDNs textareas + simulating ENTER key pressing after the TAB key event - END -->
What about this.... Im to bored at work i think..
http://jsbin.com/uqalej/3/
HTML:
<input/>
<textarea id="t1"></textarea>
<textarea id="t2"></textarea>
<input/>
<button onClick='window.toggleBetween=true;'>Init</button>
<button onClick='window.toggleBetween=false;'>Destroy</button>
JS:
var d = document,
t1 = d.getElementById("t1"),
t2 = d.getElementById("t2"),
nodeType, nodeTypes = [],
i, iLen,
y, yLen;
nodeTypes.push( d.getElementsByTagName("textarea") );
nodeTypes.push( d.getElementsByTagName("input") );
nodeTypes.push( d.getElementsByTagName("select") );
i = 0;
iLen = nodeTypes.length;
for ( ; i < iLen; i++ ) {
nodeType = nodeTypes[i];
y = 0;
yLen = nodeType.length;
for ( ; y < yLen; y++ ) {
if ( nodeType[y] != t1 && nodeType[y] != t2 ) {
nodeType[y].onfocus = function() {
if ( window.toggleBetween )
t1.focus();
};
}
}
}
Using javascript on page load:
document.getElementById("textarea1").focus();
document.getElementById('textarea1').tabIndex="1";
document.getElementById('textarea2').tabIndex="2";
im writing payment page and there is 4 textbox for credit card number entry and after for digits set focus on another control i did for first textbox my javascript code works well but other textboxes doesnt work... here is my code...:
<script type="text/javascript">
function Length_txtCardNumber1_Validator() {
if (document.getElementById('<%= txtCardNumber1.ClientID %>').value.length = 4) {
document.getElementById('<%= txtCardNumber2.ClientID %>').focus();
return (false);
}
return (true);
}
function Length_txtCardNumber2_Validator() {
if (document.getElementById('<%= txtCardNumber2.ClientID %>').value.length = 4) {
document.getElementById('<%= txtCardNumber3.ClientID %>').focus();
return (false);
}
return (true);
}
function Length_txtCardNumber3_Validator() {
if (document.getElementById('<%= txtCardNumber3.ClientID %>').value.length = 4) {
document.getElementById('<%= txtCardNumber4.ClientID %>').focus();
return (false);
}
return (true);
}
</script>
code behind onpage_load :
txtCardNumber1.Attributes.Add("onkeypress", "return Length_txtCardNumber1_Validator()");
txtCardNumber2.Attributes.Add("onkeypress", "return Length_txtCardNumber2_Validator()");
txtCardNumber3.Attributes.Add("onkeypress", "return Length_txtCardNumber3_Validator()");
thank you...
Use == for comparison.
function Length_txtCardNumber3_Validator() {
if (document.getElementById('<%= txtCardNumber3.ClientID %>').value.length == 4) {
document.getElementById('<%= txtCardNumber4.ClientID %>').focus();
return (false);
}
return (true);
}
You can have "generic" code without depending on ID or name of the textboxes, plus allowing only digits as a bonus.
First, wrap all textboxes with single container and give them maxlength like this:
<div id="CreditCardPanel">
<asp:Textbox id="txtCardNumber1" runat="server" Columns="3" MaxLength="4" /> -
<asp:Textbox id="txtCardNumber2" runat="server" Columns="3" MaxLength="4" /> -
<asp:Textbox id="txtCardNumber3" runat="server" Columns="3" MaxLength="4" /> -
<asp:Textbox id="txtCardNumber4" runat="server" Columns="3" MaxLength="4" />
</div>
Now all you have to do is having such JS code and it's all done:
<script type="text/javascript">
var arrCreditCardInputs = [];
window.onload = function WindowLoad() {
var arrInputs = document.getElementById("CreditCardPanel").getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oCurInput = arrInputs[i];
if (oCurInput.type == "text") {
oCurInput.onkeypress = function(event) {
//allow digits only:
var keyCode = event.keyCode || event.which;
if (keyCode >= 48 && keyCode <= 57) {
if (this.value.length + 1 >= this.maxLength) {
var index = parseInt(this.getAttribute("arr_index"), 10);
var nextIndex = ((index + 1) % arrCreditCardInputs.length);
window.setTimeout(function() {
arrCreditCardInputs[nextIndex].focus();
}, 200);
}
return true;
}
else {
return false;
}
}
oCurInput.setAttribute("arr_index", i + "");
arrCreditCardInputs.push(oCurInput);
}
}
}
</script>
Basically, the code is taking all the textbox elements in the container, and assign their onkeypress event so that only digits can be pressed and when reaching the maximum length focus the next textbox as defined in the global array containing them.
Timer is used to allow the browser a chance to change the value of the textbox, otherwise setting focus immediately will "cancel" the key press and the value won't change.
Live test case is available here, try messing around with the code and understand how it works. :)
I bound the keyup event to the textboxes
$('#ccNumber1').bind('keyup',function () {
if ($(this).val().length == 4)
$('#ccNumber2').focus();
});