Switch between two textareas only when pressing Tab button - javascript

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";

Related

Textarea Shift+Enter for next line and Enter to submit the form

In textarea when the user presses Shift+Enter then it should continue in next new line and when he simply presses Enter it should submit the form without using submit button.
Here is the Fiddle!!
I have browsed a lot but doesn't helped me, detailed explanation appreciated
Please help me!!
Code
$('commenttextarea').keyup(function (event) {
if ( event.shiftKey && event.keyCode == 13) {
var content = this.value;
var caret = getCaret(this);
this.value = content.substring(0,caret)+"\n"+content.substring(carent,content.length-1);
event.stopPropagation();
}else if(event.keyCode == 13)
{
$('commentform').submit();
}});
First, You missed to load any jquery version
Second, you missed # before textarea and form selectors.
Also use caret not carent in line
this.value = content.substring(0,caret)+"\n"+content.substring(caret,content.length-1);
// ----------------------------------^
Full Code
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
$('#commenttextarea').keyup(function (event) {
if (event.shiftKey && event.keyCode == 13) {
var content = this.value;
var caret = getCaret(this);
this.value = content.substring(0, caret) + "\n" + content.substring(caret, content.length - 1);
event.stopPropagation();
} else if (event.keyCode == 13) {
$('#commentform').submit();
}
});
See this would work
As Rohan Kumar said: you forgot the id Selectors:
$('#commenttextarea').keyup(function (event) {
if ( event.shiftKey && event.keyCode == 13) {
var content = this.value;
var caret = getCaret(this);
this.value = content.substring(0,caret)+"\n"+content.substring(carent,content.length-1);
event.stopPropagation();
}else if(event.keyCode == 13)
{
$('#commentform').submit();
}});

Advancing Stage in jQuery

I have the following code, I'm relatively new to JavaScript, so can anyone tell me why it isn't advancing to stage 1 + show me how it's done?
var textContainer = '#text';
var inputLine = 'input';
var username = null;
var stage = 0;
$(function(){
if(0 == stage){
$(function(){
$(textContainer).text('What is your name?');
$(inputLine).focus();
$(inputLine).keypress(function(e){
if (e.keyCode == 13 && !e.shiftKey) {
e.preventDefault();
username = $(this).val();
$(this).val('');
stage = 1;
}
});
});
}
if(1 == stage){
$(textContainer).text('Hi there, ' + username + '.');
}
});
What you have there doesn't make much sense, so I'm guessing this is what you're trying to do :
$(function(){
var textContainer = $('#text'),
inputLine = $('input');
textContainer.text('What is your name?');
inputLine.focus().on('keyup', function(e){
if (e.which === 13) {
e.preventDefault();
textContainer.text('Hi there, ' + this.value + '.');
this.value = "";
}
});
});
FIDDLE
There is no way stage could be anything other than zero right after it's set to zero?
What happens inside the event handler, happens "later", so checking stage after the event handler still gives you ... wait for it .... zero ?

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();
}
});
});

How to handle <tab> in textarea?

I would like a textarea that handles a situation of pressing tab key.
In default case if you press a tab key then focus leaves the textarea. But what about the situation when user wants to type tab key in textarea?
Can I catch this event and return focus to the textarea and add a tab to a current cursor position?
You can: http://jsfiddle.net/sdDVf/8/.
$("textarea").keydown(function(e) {
if(e.keyCode === 9) { // tab was pressed
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var $this = $(this);
var value = $this.val();
// set textarea value to: text before caret + tab + text after caret
$this.val(value.substring(0, start)
+ "\t"
+ value.substring(end));
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
e.preventDefault();
}
});
Here is a modified version of pimvdb's answer that doesn't need JQuery:
document.querySelector("textarea").addEventListener('keydown',function(e) {
if(e.keyCode === 9) { // tab was pressed
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var target = e.target;
var value = target.value;
// set textarea value to: text before caret + tab + text after caret
target.value = value.substring(0, start)
+ "\t"
+ value.substring(end);
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
e.preventDefault();
}
},false);
I tested it in Firefox 21.0 and Chrome 27. Don't know if it works anywhere else.
Good god, all previous answers failed to provide the commonly decent (i.e. for programmers) tab control.
That is, a hitting TAB on selection of lines will indent those lines, and SHIFTTAB will un-indent them.
_edited (Nov 2016): keyCode replaced with charCode || keyCode, per KeyboardEvent.charCode - Web APIs | MDN
(function($) {
$.fn.enableSmartTab = function() {
var $this;
$this = $(this);
$this.keydown(function(e) {
var after, before, end, lastNewLine, changeLength, re, replace, selection, start, val;
if ((e.charCode === 9 || e.keyCode === 9) && !e.altKey && !e.ctrlKey && !e.metaKey) {
e.preventDefault();
start = this.selectionStart;
end = this.selectionEnd;
val = $this.val();
before = val.substring(0, start);
after = val.substring(end);
replace = true;
if (start !== end) {
selection = val.substring(start, end);
if (~selection.indexOf('\n')) {
replace = false;
changeLength = 0;
lastNewLine = before.lastIndexOf('\n');
if (!~lastNewLine) {
selection = before + selection;
changeLength = before.length;
before = '';
} else {
selection = before.substring(lastNewLine) + selection;
changeLength = before.length - lastNewLine;
before = before.substring(0, lastNewLine);
}
if (e.shiftKey) {
re = /(\n|^)(\t|[ ]{1,8})/g;
if (selection.match(re)) {
start--;
changeLength--;
}
selection = selection.replace(re, '$1');
} else {
selection = selection.replace(/(\n|^)/g, '$1\t');
start++;
changeLength++;
}
$this.val(before + selection + after);
this.selectionStart = start;
this.selectionEnd = start + selection.length - changeLength;
}
}
if (replace && !e.shiftKey) {
$this.val(before + '\t' + after);
this.selectionStart = this.selectionEnd = start + 1;
}
}
});
};
})(jQuery);
$(function() {
$("textarea").enableSmartTab();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="10" cols="80">
/* Just some code to edit with our new superTab */
(function($) {
$.fn.enableSmartTab = function() {
$this = $(this);
$this.keydown(function(e) {
if ((e.charCode === 9 || e.keyCode === 9) && !e.metaKey && !e.ctrlKey && !e.altKey) {
e.preventDefault();
}
}
}
}
</textarea>
In Vanilla (Default) JS this would be:
var textareas = document.getElementsByTagName('textarea');
if ( textareas ) {
for ( var i = 0; i < textareas.length; i++ ) {
textareas[i].addEventListener( 'keydown', function ( e ) {
if ( e.which != 9 ) return;
var start = this.selectionStart;
var end = this.selectionEnd;
this.value = this.value.substr( 0, start ) + "\t" + this.value.substr( end );
this.selectionStart = this.selectionEnd = start + 1;
e.preventDefault();
return false;
});
}
}
textarea {
border: 1px solid #cfcfcf;
width: 100%;
margin-left: 0px;
top: 0px;
bottom: 0px;
position: absolute;
}
<textarea>
var x = 10;
var y = 10;
</textarea>
Found this while searching google. I made a really short one that can also indent and reverse indent selections of text:
jQ(document).on('keydown', 'textarea', function(e) {
if (e.keyCode !== 9) return;
var Z;
var S = this.selectionStart;
var E = Z = this.selectionEnd;
var A = this.value.slice(S, E);
A = A.split('\n');
if (!e.shiftKey)
for (var x in A) {
A[x] = '\t' + A[x];
Z++;
}
else
for (var x in A) {
if (A[x][0] == '\t')
A[x] = A[x].substr(1);
Z--;
}
A = A.join('\n');
this.value = this.value.slice(0, S) + A + this.value.slice(E);
this.selectionStart = S != E ? S : Z;;
this.selectionEnd = Z;
e.preventDefault();
});
Enable tabbing inside (multiple) textarea elements
Correcting #alexwells answer and enable a live demo
var textAreaArray = document.querySelectorAll("textarea");
for (var i = textAreaArray.length-1; i >=0;i--){
textAreaArray[i].addEventListener('keydown',function(e) {
if(e.keyCode === 9) { // tab was pressed
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var target = e.target;
var value = target.value;
// set textarea value to: text before caret + tab + text after caret
target.value = value.substring(0, start)
+ "\t"
+ value.substring(end);
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
e.preventDefault();
}
},false);
}
<textarea rows="10" cols="80"></textarea>
<textarea rows="10" cols="80"></textarea>

Categories