How do you tab through text in html text input? - html

So I need a way of being able to tab to the next line in an html text input without it skipping to the next html input, is this possible?

You can do it by Jquery:
Activating next input field in form on enter
Focus on next input field inside table with enter key press
focusNextInputField With jsfiddle demo
Easiest one is:
$("input").change(function() {
var inputs = $(this).closest('form').find(':input');
inputs.eq( inputs.index(this)+ 1 ).focus();
});
If these solutions doesn't help then provide your code, so that it will be easier to understand.

If you really are trying to MAKE a textarea field where users can tab, you don't need jQuery.
See this jsFiddle : http://jsfiddle.net/2wAzx/13/
function enableTab(id) {
var el = document.getElementById(id);
el.onkeydown = function(e) {
if (e.keyCode === 9) { // tab was pressed
// get caret position/selection
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
// set textarea value to: text before caret + tab + text after caret
this.value = val.substring(0, start) + '\t' + val.substring(end);
// put caret at right position again
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
return false;
}
};
}
// Enable the tab character onkeypress (onkeydown) inside textarea...
// ... for a textarea that has an `id="my-textarea"`
enableTab('my-textarea');
Also, if that is your question, i'd recommend marking it as a duplicate since it has been asked more than once on SO...

Related

how to toggle appended elements using multiple buttons and pass info to the output JQuery

I have asked kind of a similar question before : how to toggle using multiple buttons and pass info to the output JQuery
It was answered well, but this time I am using a different approach in the code thus a new question.
I am trying to toggle info and append a div using three different buttons.
Here is The code https://jsfiddle.net/YulePale/nruew82j/40/
JavaScript
document.getElementById("brazil").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("brazil").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("draw").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("draw").value
para.innerHTML = 'This two teams have played each other 4 times ' +
`${homeTeam}` + ':' <br> <input type="text" value="${homeTeam}" id="myInput">
<button onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
document.getElementById("russia").addEventListener('click', function(e){
if(e.currentTarget.dataset.triggered) return;
e.currentTarget.dataset.triggered = true;
AppendFunction();
function AppendFunction() {
var para = document.createElement("p");
var homeTeam = document.getElementById("russia").value
para.innerHTML = 'This is the national team of ' + `${homeTeam}` + ':'
<br> <input type="text" value="${homeTeam}" id="myInput"><button
onclick="myFunction()">Copy text</button>';
var element = document.getElementById("gugu");
element.appendChild(para)
}
})
PS: I don't know why the javascript code is not working in fiddle yet it is working on my computer.
If you look at the code I am basically trying to toggle a div with info on various teams. If it is Brazil the div comes with info on Brazil if Russia, info on Russia.
The problem with my current code is that it keep on appending the divs instead of
toggling them. How can I toggle them? like this: https://jsfiddle.net/YulePale/7jkuoc93/
Instead of having them append another div each time I click a different button?
............................................................................................
PS: EDIT & UPDATE:
#Twisty, I forked the code from your fiddle and tried to implement it when working with more than one row of buttons. The code works well but I was unable to append a different and separate element for each row each time I click on a button on that row.
I tried putting the appended element as a class:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/34/
Also tried putting it as an id:
Here is the code: https://jsfiddle.net/YulePale/a9L1nqvm/38/
How can I put it in a way that each row appends it's own separate element and I would also like users to be able to copy using the copy button without the element disappearing. How do I make it in such a way that the element only disappears only when I click outside the respective:
<div class="col.buttonCol " id="buttons-div">
and also disappears when I click another row of buttons?
Also in your answer you said you would have used text boxes instead of appending this way. I checked the modals out and they all appear on the browser like alerts can you please point me to a resource that show how you can use a modal that works like an appending element instead of one that acts as an alert? Thank you.
Here is the link to the modals I saw: https://getbootstrap.com/docs/4.0/components/modal/
I converted all your JavaScript to jQuery since you posted this in the jquery-ui, I am assuming you want to work with jQuery.
I will often organize my functions first and then the interactive actions.
JavaScript
$(function() {
function myFunction() {
//Do Stuff
}
function AppendFunction(id) {
var para = $("<p>");
var home = $("#" + id).val();
para.append("This is the national team of " + home + ":", $("<br>"), $("<input>", {
type: "text",
value: home,
id: "myInput"
}), $("<button>").html("Copy Text").click(myFunction));
$("#gugu").html(para);
}
function emptyOnDocumentClick(event) {
var action = $(".triggered").length;
$(".triggered").removeClass("triggered");
return !action;
}
$("#brazil, #russia").on('click', function(e) {
if ($(this).hasClass("triggered")) {
return;
}
$(this).addClass("triggered");
var myId = $(this).attr("id");
AppendFunction(myId);
});
$(document).on("click", function(e) {
if (emptyOnDocumentClick(e)) {
$("#gugu").html("");
}
});
});
Working Example: https://jsfiddle.net/Twisty/nruew82j/91/
The basic concept here is a dialog and if it were me, I would use a dialog box either from BootStrap or jQuery UI. You're not doing that, so we're create the content and append it to a specific <div>. Then, like in your previous question, you just detect a click on the document and decide what that will do. In this case, I emptied the content of the <div> that we'd previously appended content to.
Hope that helps.

How to set Text Input field to focus when user start typing on page

I am trying to autofocus on a text input when a user starts typing on a webpage.
i have tried this, but this is only for page load
<input type="text" name="text_input" autofocus>
How can i set it so it will focus when the user starts typing on the page
Use jQuery.
$('body').on('keydown', function() {
var input = $('input[name="text_input"]');
if(!input.is(':focus')) {
input.focus();
}
});
Edit
If you only want this to happen once, you can set some sort of flag, like this:
var flag = false;
$('body').on('keydown', function() {
var input = $('input[name="text_input"]'),
if(!input.is(':focus') && flag === false) {
input.focus();
flag = true;
}
});
Building on Josh Beam's answer, if you want to also tack whatever key the user pressed to the end of the input you could do something like the code below. It also only triggers if the pressed key is a number or letter, so it won't take focus if the user presses an arrow key, page up, etc.
$('body').on('keydown', function(keyPress) {
var input = $('input[name="text_input"]');
if(!input.is(':focus') && keyPress.key.match(/^[0-9a-zA-Z]+$/)) {
input.focus();
input.val(input.val()+keyPress.key);
}
});

How to make HTML5 contenteditable div allowing only text in firefox?

I want to make div with contentEditable attribute which is allowing only text. It's easily achievable in Chrome by using:
<div contenteditable="plaintext-only"></div>
However it doesn't work in Firefox. Is there a way how to make text-only contenteditable div in Firefox ? I know it is possible, because Google Plus has such div, but I don't know how they do it.
I ran into this problem myself. Here is my solution which I have tested in Firefox and Chrome:
Ensure the contenteditable div has the css white-space: pre, pre-line or pre-wrap so that it displays \n as new lines.
Override the "enter" key so that when we are typing, it does not create any <div> or <br> tags
myDiv.addEventListener("keydown", e => {
//override pressing enter in contenteditable
if (e.keyCode == 13)
{
//don't automatically put in divs
e.preventDefault();
e.stopPropagation();
//insert newline
insertTextAtSelection(myDiv, "\n");
}
});
Secondly, override the paste event to only ever fetch the plaintext
//override paste
myDiv.addEventListener("paste", e => {
//cancel paste
e.preventDefault();
//get plaintext from clipboard
let text = (e.originalEvent || e).clipboardData.getData('text/plain');
//insert text manually
insertTextAtSelection(myDiv, text);
});
And here is the supporting function which inserts text into the textContent of a div, and returns the cursor to the proper position afterwards.
function insertTextAtSelection(div, txt) {
//get selection area so we can position insert
let sel = window.getSelection();
let text = div.textContent;
let before = Math.min(sel.focusOffset, sel.anchorOffset);
let after = Math.max(sel.focusOffset, sel.anchorOffset);
//ensure string ends with \n so it displays properly
let afterStr = text.substring(after);
if (afterStr == "") afterStr = "\n";
//insert content
div.textContent = text.substring(0, before) + txt + afterStr;
//restore cursor at correct position
sel.removeAllRanges();
let range = document.createRange();
//childNodes[0] should be all the text
range.setStart(div.childNodes[0], before + txt.length);
range.setEnd(div.childNodes[0], before + txt.length);
sel.addRange(range);
}
https://jsfiddle.net/1te5hwv0/
Sadly, you can’t. As this answer points out the spec only specifies true, false and inherit as valid parameters. The subject seems to have been discussed but if I’m not mistaken only Webkit implements support for plaintext-only.

Contenteditable in HTML tables

With the code:
<table>
<tr><td contenteditable>My_Name</td><td>Surname</td></tr>
<tr><td contenteditable>My_Name2</td><td>Surname2</td></tr>
</table>
You can edit a cell in an HTML table. My problem is when I edit the cell and press enter, it creates a new line in cell. What I really would like is, if I press enter I go to the cell just below that cell I just edited so that I can edit that cell.
Currently I have to use the mouse to go to the next cell, but if I can press enter and go to the cell, it will help me edit the cells a bit faster. Plus the updated data will be stored in my database, so I also don't want unnecessary space stored in the database.
But I am not sure what I can do. Is there any example I can look at?
I've built a fully editable table "Grid" in JS and HTML before.. and logic behind it simply is as following:
1- in your table after you layout all your cols, add an action col and add a "edit" link in each row that points to an Edit function, in this Edit link pass the row index so.. it will look like that:
<a href='javascript:void(0)' id='EditBtn' onclick='Edit("+ rowIndex +")'>Edit</a>"
2- your Edit function will simple loop on your columns using that rowIndex and replace the text values with a text box tag
"<input type='text' id='nominal' id='editableField' >" + tdTxt + "</input >"
Just avoid making the "Edit" column Editable
now, you should have a fully editable row..
on last thing, is to Add beside the "Edit" link a "Cancel" link that will loop again on the Row columns like the Edit link and Replace the Text tags with a Span or just pure html with the "" original values..
You may wonder how I will have the origianl td values, well in this case we added a hidden field that carrys the td value, so when the user click cancel after edit. we get the cell original value before edit,
hope that helps.
Disclaimer: This code requires JQuery.
Something like this? http://jsfiddle.net/v2Tdn/3/
$('td').keypress(function (evt) {
if (evt.which == 13) {
evt.preventDefault();
var cellindex = $(this).index()
// get next row, then select same cell index
var rowindex = $(this).parents('tr').index() + 1
$(this).parents('table').find('tr:eq(' + rowindex + ') td:eq(' + cellindex + ')').focus()
}
})
*** UPDATE ***
Note, I've updated the jsfiddle to also select the text when you press enter. For the previous example which only focused on the next TD, please use http://jsfiddle.net/v2Tdn/1/ .
Demo showing how to capture and preventDefault action on enter key press.
Here's the code that does the trick:
$('table').bind('keypress', function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
console.log("Enter pressed");
e.preventDefault();
// focus 'td' in next column using jQuery '.focus()'
}
return false;
});
You have to understand that 'contenteditable' is making your markup behaving like a <textarea>. Normally, people press the tab key to skip from a form field to another.
Using jQuery javascript library, you can read the keyboard for enter key, javascript it to 'escape' the edition by setting focus somewhere else, perhaps the next td with contenteditable. :
$(document).ready(function () {
var $editableTd = $('td[contenteditable]');
$editableTd.bind('keypress', function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
var ind = $editableTd.index(this); //check next td to target
$editableTd.eq(ind + 1).focus(); //set focus to it
e.preventDefault(); //do 'nothing'
}
});
});
jsFiddled here

Tabbing through an HTML form on OS X, any way to force it to stop on all form elements?

First question here, be gentle. :)
In OS X, tabbing through an HTML form, you'll find that it only stops on text boxes and lists. I need it to stop on all form inputs (not strictly inputs, all form elements that collect data).
As far as I'm aware this can only be configured in System Preferences under Keyboard Shortcuts, but obviously we don't have control over that...
Anybody have any ideas? I'd hate to have write something in jQuery to solve something that seems so trivial.
Thanks!
From my previous question:
Stupid OSX Settings:
You have to change this in System Preferences and there is no way to do it otherwise (to the best of my knowledge).
What you could try is to write a jQuery trigger for any input that has focus, see if the "Tab" key was hit, and if so jump to the next tabindex element.
I'd do something like this to force Safari to behave. The drawback is that you preventDefault on the normal navigator tabulation, which may be a bigger problem for accessibility in some situations. But I doubt it.
var Tab = {};
Tab.i = 1,
Tab.items = 0;
function fixTabulation () {
/* This can be used to auto-assign tab-indexes, or
# commented out if it manual tab-indexes have
# already been assigned.
*/
$('input, select, textarea').each(function(){
$(this).attr('tabindex', Tab.i);
Tab.i++;
Tab.items++;
});
Tab.i = 0;
/* We need to listen for any forward or backward Tab
# key event tell the page where to focus next.
*/
$(document).on({
'keydown' : function(e) {
if (navigator.appVersion.match("Safari")) {
if (e.keyCode == 9 && !e.shiftKey) { //Tab key pressed
e.preventDefault();
Tab.i != Tab.items ? Tab.i++ : Tab.i = 1;
$('input[tabindex="' + Tab.i + '"], select[tabindex="' + Tab.i + '"], textarea[tabindex="' + Tab.i + '"]').not('input[type="hidden"]').focus();
}
if (e.shiftKey && e.keyCode == 9) { //Tab key pressed
e.preventDefault();
Tab.i != 1 ? Tab.i-- : Tab.i = Tab.items;
$('input[tabindex="' + Tab.i + '"], select[tabindex="' + Tab.i + '"], textarea[tabindex="' + Tab.i + '"]').not('input[type="hidden"]').focus();
}
}
}
});
/* We need to update Tab.i if someone clicks into
# a different part of the form. This allows us
# to keep tabbing from the newly clicked input
*/
$('input[tabindex], select[tabindex], textarea[tabindex]').not('input[type="hidden"]').focus(function(e) {
Tab.i = $(this).attr('tabindex');
console.log(Tab.i);
});
}
$(document).ready(function() {
fixTabulation();
});
It's a bit hacky, but it's quite better than telling your users to go change their Safari settings in System Prefs, lol.