window.getSelection() for contenteditable div *on click* - javascript

I have a contenteditable div and want to get the user's selection when they click a span.
My problem is that when I click the span, the selection gets unselected so window.getSelection().toString() returns ''.
How can I get this to work on click of a span?
I know the actual getSelection() works, because if I wrap window.getSelection().toString() in a setTimeout of 5 seconds, after 5 seconds, I get the selected text!
My code:
$('#btn').click(function() {
console.log(window.getSelection().toString()); //returns ''
});
#btn {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='btn'>get selection</span>
<br><br>
<div id='ce' contenteditable='true'>test</div>

You can store the selection when there is a click on your contenteditable div, then return it when you click on the button.
document.querySelector("#ce").addEventListener(function(){
userSelection= window.getSelection().toString();
});
document.querySelector("#btn").addEventListener("mouseup",function(){
document.querySelector("#selection").innerHTML=
"You have selected:<br/><span class='selection'>" + userSelection +"</span>";
});
http://jsfiddle.net/xnvp38u3/

Since there is no event you can use to specifically detect a 'select' or 'deselect', you'll have to listen to a mouseup event and populate a "cache variable" that can store the selection in the memory:
var selection = '';
document.getElementById('ce').onmouseup = function(){
selection = window.getSelection().toString();
};
document.getElementById('btn').onclick = function(){
console.log(selection);
};
Or, provided you have jQuery, you could try this more complaint version, which also factors in keyboard-based selections:
var selection = '', shifted = false;
$('#ce').on('mouseup keyup keydown', function(e){
if (e.type === 'keydown') {
shifted = e.shiftKey;
return;
}
if (
e.type === 'mouseup' ||
(shifted && (e.keyCode === 39 || 37 || 38 || 40))
){
selection = window.getSelection().toString();
}
});
$('#btn').on('click', function(){
console.log(selection);
});

Related

JS Function Not working from KeyCode / How can i call this JS function with keyboard key

Here is a simple script function getSelectedText() that is working on button click. It means that when we select any text and click on the button, the function is creating a new NEWCLASS div successfully. But now I want to use a shortcut key, like CTRL+W to get selected text in the NEWCLASS div.
I tried this code but it doesn't work. Please, check it and let me know what mistake I am making here.
var input = document.getElementsByTagName("body")[0];
input.addEventListener("keyup", function(event) {
if (event.keyCode === 37) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
My code:
// Function to get the Selected Text
function getSelectedText() {
var selectedText = '';
// #### create a new element with variable (nw) #### //
var nw = document.createElement("div"); // Element's tag
nw.className = "NEWCLASS"; // Element's class name
// some applied style
// window.getSelection
if (window.getSelection) {
selectedText = window.getSelection();
}
// document.getSelection
else if (document.getSelection) {
selectedText = document.getSelection();
}
// document.selection
else if (document.selection) {
selectedText =
document.selection.createRange().text;
} else return;
// #### get the Selected text appended to body #### //
nw.innerHTML = selectedText;
document.getElementsByClassName('maintitle')[0].prepend(nw); // Append element to body
}
<button id="mybtn" onclick="getSelectedText()">Button</button>
<p>Select any part of this sentence and press the button. Select any part of this sentence and press the button. Select any part of this sentence and press the button</p>
<div class="maintitle"> </div>
the ctrl key with w will close the chrome browser so I used "Z" key for that you can replace the key code with whatever you want.
Find the keycodes here
const keySelected = new Set();
document.addEventListener('keydown', (e) => {
keySelected.add(e.which);
if(keySelected.has(17) && keySelected.has(90)){
getSelectedText();
}
});
document.addEventListener('keyup', (e) => {
keySelected.delete(e.which);
});
/*
//jquery code if anyone want
$(document).ready(function(){
const keySelected = new Set();
$(document).keydown(function (e) {
keySelected.add(e.which);
if(keySelected.has(17) && keySelected.has(90)){
getSelectedText()
}
});
$(document).keyup(function (e) {
keySelected.delete(e.which);
});
});
*/
// Function to get the Selected Text
function getSelectedText() {
var selectedText = '';
// #### create a new element with variable (nw) #### //
var nw = document.createElement("div"); // Element's tag
nw.className = "NEWCLASS"; // Element's class name
// some applied style
// window.getSelection
if (window.getSelection) {
selectedText = window.getSelection();
}
// document.getSelection
else if (document.getSelection) {
selectedText = document.getSelection();
}
// document.selection
else if (document.selection) {
selectedText =
document.selection.createRange().text;
} else return;
// #### get the Selected text appended to body #### //
nw.innerHTML = selectedText;
document.getElementsByClassName('maintitle')[0].prepend(nw); // Append element to body
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="mybtn" onclick="getSelectedText()">Button</button>
<p>
Select any part of this sentence
and press the button. Select any part of this sentence
and press the button. Select any part of this sentence
and press the button
</p>
<div class="maintitle"> </div>
You don't need to recall the event on the button, you should be capable of detect the press of the key you want and call the function, like:
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.code === 'keyW') {
getSelectedText();
}
});
Ctrl+W is not such a good choice, as on Windows it is a common shortcut key for closing the current Window or document, so your script will not even get the key event.
But I'll pick Ctrl+Y instead.
You should not use the deprecated keyCode property -- nor the which property which another answer suggests -- notice the red notice in the MDN documentation.
It is even easier with the key property. And you can use the ctrlKey property to know whether the control key is down.
I would use the keydown instead of the keyup event, as you can then cancel any default effect of the key, with a call to cancelDefault.
document.addEventListener("keydown", (event) => {
if (event.ctrlKey && event.key == "y") {
event.preventDefault();
getSelectedText();
}
});
// Your original code:
function getSelectedText() {
var selectedText = '';
var nw = document.createElement("div"); // Element's tag
nw.className = "NEWCLASS"; // Element's class name
if (window.getSelection) {
selectedText = window.getSelection();
} else if (document.getSelection) {
selectedText = document.getSelection();
} else if (document.selection) {
selectedText = document.selection.createRange().text;
} else return;
nw.innerHTML = selectedText;
document.getElementsByClassName('maintitle')[0].prepend(nw);
}
<button id="mybtn" onclick="getSelectedText()">Button</button>
<p>Select any part of this sentence and press the button or enter Ctrl+Y.
Select any part of this sentence and press the button or enter Ctrl+Y.
Select any part of this sentence and press the button or enter Ctrl+Y.
</p>
<div class="maintitle"> </div>
This should work
var input = document.getElementsByTagName("body")[0];
input.keypress("w", function(event) {
if (event.ctrlKey) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});

jQuery - get current text selection within input field

I have several input boxes with the same class name. I want to be able to get the currently highlighted text and know exactly which input box that text is in. My current method is as so:
$(document).on("mouseup", ".element", function(){
var text = "";
var activeEl = document.activeElement;
var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
if (
(activeElTagName == "textarea") || (activeElTagName == "input" &&
/^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
(typeof activeEl.selectionStart == "number")
) {
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
} else if (window.getSelection) {
text = window.getSelection().toString();
}
});
This gives me the current text selection and I can call $(this) to access the element that the highlighted text is in.
The problem with my current method however, is that if you begin the click and then drag outside the text box, say just outside the left edge of the text box, you'll have highlighted text within the box but the event will not register, since the mouse click ended outside the scope of the input field. How can I remedy this issue?
You can bind more than one event to a handler.
So just bind mouseleave too!
$(document).on("mouseup mouseleave", ".element", function(){
You can use an onselect event on the input boxes. When you select the text, an onselect event is reigistered. Afterwards, you can find the starting point of the highlighted text and the ending point of the highlighted text.
See snippet below
$(".boxes").on('select', function() {
if (window.getSelection) {
text = window.getSelection().toString();
var start_index = this.selectionStart;
var end_index = this.selectionEnd;
console.log(this.value.substr(start_index, end_index));
}
}) //end mouseover
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="in1" class="boxes">
<input id="in1" class="boxes">
<input id="in1" class="boxes">
<input id="in1" class="boxes">
<input id="in1" class="boxes">
You can set a variable like isMouseDown outside of the scope of the event handler like so:
var isMouseDown = false;
$(document).on("mousedown", ".element", function(){
isMouseDown = true;
});
$(document).on("mouseup", document, function(){
if (isMouseDown) {
var text = "";
var activeEl = document.activeElement;
var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
if (
(activeElTagName == "textarea") || (activeElTagName == "input" &&
/^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
(typeof activeEl.selectionStart == "number")
) {
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
} else if (window.getSelection()) {
text = window.getSelection().toString();
}
}
isMouseDown = false;
});

What do selectionStart and selectionEnd signify for textarea?

I came across following code snippet to insert enter into the the text in a textarea where ctrl + enter is pressed.
$("#txtChatMessage").keydown(MessageTextOnKeyEnter);
function MessageTextOnKeyEnter(e) {
console.log(this.selectionEnd);
if (e.keyCode == 13) {
if (e.ctrlKey) {
var val = this.value;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
var start = this.selectionStart;
this.value = val.slice(0, start) + "\n" + val.slice(this.selectionEnd);
this.selectionStart = this.selectionEnd = start + 1;
} else if (document.selection && document.selection.createRange) {
this.focus();
var range = document.selection.createRange();
range.text = "\r\n";
range.collapse(false);
range.select();
}
}
return false;
}
}
What I don't understand is what do selectionStart and selectionEnd mean here ? According to documentation that I read, selectionStart-End contain the start-end of selected text in the input element. However, here no text is explicitly selected. On doing console.log I could see that both these properties always have some value even when the text is not selected. Why is that?
selectionStart specifies the index of the selection/highlighted text within the <textarea>. Similarly, selectionEnd specifies the index where the selection ends. Initially, they are set to 0, and if the <textarea> is focused but no text is selected, the selectionStart and selectionEnd values will be the same, and reflect the position of the caret within the value of the <textarea>. On un-focus or blur of the <textarea>, they will remain at the last value that they were set to before the blur event.
Here's a fiddle you can play with:
http://jsfiddle.net/5vd8pxct/
The if block in question appears to handle cross-browser compatibility. document.selection is for IE. selectionStart and selectionEnd seem to work elsewhere. I don't have IE on my machine to experiment with it, and I'm using Chrome. It appears from my fiddle that the default start/end are 0 when the page loads. If you click into/select in the box, the start end will be as expected. If you click outside the box, the positions within the box are remembered.
document.selection is undefined in Chrome.
Your code does not work. You mix regular JavaScript and JQuery. I would suggest to start with plain JavaScript. Generally, in JavaScript this is a reference to the object on which the code will be executed.
Take a look at the following example:
<html>
<head>
<script type="text/javascript">
window.addEventListener("load", function () {
var chat = document.getElementById('txtChatMessage'); // get textarea
chat.addEventListener('keydown', function (event) { //add listener keydown for textarea
event = event || window.event;
if (event.keyCode === 13) { //return pressed?
event.preventDefault();
if (this.selectionStart != undefined) {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var selectedText = this.value.substring(startPos, endPos);
alert("Hello, you've selected " + selectedText);
}
}
})
});
</script>
</head>
<body>
<textarea id="txtChatMessage" cols="40" rows="10"></textarea>
</body>
</html>
At first an event listener "onLoad" has been registered. Within this function we get a reference to the textarea object. On this object a new event listener "onKeyDown" has been registered. Within this function this refers to the textarea (chat) object. With the help of the event object, we can ask for the pressed key event.keyCode === 13. With this (textarea) and its attributes selectionStart and selectionEnd we get the selected text.

Temporarily disable all currently active jQuery event handlers

I am making a TD element of table editable on double click:
$(document).on("dblclick", "#table>tbody>tr>td.cell", function(e) {
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function() {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
});
function stub(e) {
e.stopImmediatePropagation();
return false;
}
But when i double click on the text inside the editable div, the double click event propagates to the parent td causing undesired consequences. There are also other events (select, mousedown, etc) i want to prevent, so writing a stub for each of them doesn't look nice to me.
Is there a way to disable all currently active jQuery event handlers and enable them afterwards? Or somewhow stop propagating all events from the editable div to its parents?
Or somewhow stop propagating all events from the editable div to its parents?
It may not be very palatable, but it's not that bad to specifically disable the events:
$(this).on("select mousedown mouseup dblclick etc", false);
(Assuming this refers to the cell you're editing.)
There is a limited number of events, after all, and on allows you to list them in a space-delimited string and disable them by passing false.
You can then re-enable them by passing the same list and false again into off.
Use on / off JQuery methods :
var myFunction = function(e) {
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function() {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
};
function stub(e) {
e.stopImmediatePropagation();
return false;
}
//Active the events
$(document).on("dblclick", "#table>tbody>tr>td.cell", myFunction);
//Disable the events
$(document).off("dblclick", "#table>tbody>tr>td.cell",myFunction);
//Reactive the events
$(document).on("dblclick", "#table>tbody>tr>td.cell", myFunction);
Update
You can also manage a variable set to true if the event must not be taking into account :
var skipEvent = true;
$(document).on("dblclick", "#table>tbody>tr>td.cell", function (e) {
//Check variable and skip if true
if (skipEvent)
return false;
if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey)
// need left button without keyboard modifiers
return;
reset_selection();
var editor = document.createElement("div");
editor.setAttribute("contenteditable", "true");
editor.innerHTML = this.innerHTML;
this.innerHTML = '';
// this.style.padding = 0;
this.appendChild(editor);
$(document).on("*", stub);
editor.onblur = function () {
// this.parentNode.setAttribute("style", "");
this.parentNode.innerHTML = this.innerHTML;
sys.editor = null;
$(document).off("*", stub);;
};
editor.focus();
});

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