Focus next Element in tabindex when pressing Enter key - javascript

Users on my application are used to press "Enter" when changing to the next input instead of "Tab", so I've been trying to change focus to the next Element in tabindex when pressing "Enter" instead of "Tab" given this code:
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>
Now that I've achieved it I want to share my solution so the next person who has this problem finds the solution quickly.

Solution
In my case I aimed $("#data") for the function to trigger but you can use it with $(window).
This function will get triggered on keydown, will check if the key is "Enter" (wich key code is 13), look for the next element of the focused element (activeElement) according to the tabindex and then will focus it.
$("#data").keydown(function(e) {
if(e.keyCode == 13){
let active = document.activeElement;
let target = $('[tabindex="' + (active.tabIndex + 1) + '"]');
target.focus();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>
Edit
In reference to #freedomn-m 's comment, this is his code to set the tabindex attribute on the non-readonly elements:
$(() => $("#data :input:not([readonly])").attr("tabIndex", (i, a) => i));
That's the code that I was using before:
$(document).ready(function(){
let inputs = $('#data :input');
let tabindex = 0;
for(let i = 0; i < inputs.length; i++){
if($(inputs[i]).attr("readonly") !== "readonly"){
inputs[i].setAttribute("tabindex", tabindex);
tabindex++;
}
}
})

const inputs = document.querySelectorAll('#data input');
const inputsArray = Array.prototype.slice.call(inputs);
document.addEventListener('keypress', function (event) {
const key = event.which || event.keyCode;
if (key === 13) { // 13 is the keycode for the Enter key
const activeElement = document.activeElement;
const index = inputsArray.indexOf(activeElement);
if (index > -1 && index < inputsArray.length - 1) {
inputsArray[index + 1].focus();
}
}
});
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>

Related

How to validate both input text

I want to show the message "Input Number Only" if I oninput the alphabet. The first text box is successfully show but when I input alphabet into the second text box it does not show anything at the span. How to edit my code so that it will show the message after I on input the alphabet. Here my code :
function allvalidate(){
var inp = document.getElementsByClassName('text');
for(var i in inp){
if(inp[i].type == "text"){
if(!/^\d{1,}$/.test(inp[i].value)){
error.textContent = "Input Number Only";
error.style.color = "red";
return false;
}
else {
error.textContent = "";
}
return true;
break;
}
}
}
<p>Number of Customer</p>
<p><input type="text" name="people" class="text" placeholder="no.of people" size="18" maxlength="10" oninput="allvalidate()"></p>
<p>Age</p>
<p><input type="text" name="post" class="text" placeholder="postcode" size="18" maxlength="2" oninput="allvalidate()"></p>
<span id="error"></span>
Replace the following statement:
for(var i in inp){
with
for(let i=0 ;i<inp.length;i++){
A delegated event listener bound to the document can intercept and process all the input elements without needing to explicitly add the oninput event handler to each one as above. That event handler can likely also be simplified by using isNaN rather than a regex
const errspan=document.getElementById('error');
document.addEventListener('input',e=>{
errspan.textContent = "";
if( e.target.type=='text' && isNaN( e.target.value ) ) {
errspan.textContent = "Input Number Only";
}
})
#error{
color:red
}
<p>Number of Customer</p>
<p>
<input type="text" name="people" class="text" placeholder="no.of people" size="18" maxlength="10" />
</p>
<p>Age</p>
<p>
<input type="text" name="post" class="text" placeholder="postcode" size="18" maxlength="2" />
</p>
<span id="error"></span>

javascript set new data value

I have 2 input boxes.
When I input a value into the first one, the javascript function checkMyKad() is triggered.
checkMyKad() gets value in first input box, edits it, and alerts new value.
I want new to be set into second input box. How do I get new value to be shown in 2nd input box?
<div class="form-group" style="color:#0000FF; margin-left:160px;" >
<input type="text" placeholder="Please input value" id="myKadC" maxlength="4" size="10" onchange="checkMyKad()" required>
<input type="text" id="newVal" maxlength="20" size="20"/>
</div>
javascript function
function checkMyKad() {
var mykadC = $('#myKadC').val();
var newVal='Value is : '+'-'+mykadC;
alert(newVal);
$('#newValId').val(newVal);
}
You seem to target the wrong id, it should be $('#newVal')
function checkMyKad() {
var mykadC = $('#myKadC').val();
var newVal='Value is : '+'-'+mykadC;
alert(newVal);
$('#newVal').val(newVal);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" style="color:#0000FF; margin-left:160px;" >
<input type="text" placeholder="Please input value" id="myKadC" maxlength="4" size="10" onchange="checkMyKad()" required>
<input type="text" id="newVal" maxlength="20" size="20"/>
</div>
You have $('#newValId') instead of $('#newVal')
target id is wrong.
$('#newValId').val(newVal); -> $('#newVal').val(newVal);
Personally I would do something like this:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="form-group" >
<h3>Pure JavaScript</h3>
<input type="text" placeholder="Please input value" maxlength="4" size="10" onchange="checkMyKad(this)" required>
<input type="text" maxlength="20" size="20"/>
</div>
<div class="form-group" >
<h3>Using jQuery</h3>
<input type="text" placeholder="Please input value" maxlength="4" size="10" onchange="checkMyKadJQuery(this)" required>
<input type="text" maxlength="20" size="20"/>
</div>
<script type="text/javascript">
function checkMyKad(element) {
   let oldValue = element.value;
   let newValue = 'Value is : -'+oldValue;
   alert(newValue);
   element.nextElementSibling.value = newValue;
}
function checkMyKadJQuery(element) {
let oldValue = $(element).val();
   let newValue = 'Value is : -'+oldValue;
alert(newValue);
$(element).next().val(newValue);
}
</script>
Doing it like that would allow the functions to be reused.

Change input to Upper Case with CapsLock on

I would just like to know is it possible to change the input automatically to capitalized on a certain input field where the user entered a value with Caps Lock on.
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps On = TEST NAME
Expected: Test Name
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps Off = test name
Default: Test Name
I know some Names looks like Reader Van der Bank where not all the name parts are capitalized, but still would like to know if its possible. Thanks
Alternative : Think i might be using a php function to transform everything to lowercase and then capitalized.
Here is a javascript function to do that, if there is no CSS solution for it.
var id = document.getElementById("test");
function change() {
var arr = id.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
id.value = arr.join(" ");
}
id.addEventListener("change", change);
id.addEventListener("keyup", change);
<input placeholder="Brand Name" id="test" type="text" />
For multiple elements with class test
var elements = document.getElementsByClassName("test");
function change() {
var arr = this.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
this.value = arr.join(" ");
}
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener("change", change);
elements[i].addEventListener("keyup", change);
}
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
Do you want to enter all the text capitalized in the input? then u can use text-transform:uppercase in css and if u want to change it while typing you can use toUpperCase() on keyup of that input.
style="text-transform: capitalize"
(Question was edited. New Answer.)
Give your input an id, for this example let's say it's called "theInputId".
Then add an onkeypress event to it also and call the function script I've listed below.
<input placeholder="Brand Name" style="text-transform: capitalized"
type="text" id="theInputId" onkeypress="capsLock(event)">
<script>
//Script to check if Caps Lock is on.
function capLock(e){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)){
document.getElementById('theInputId').style.textTransform = 'lowercase'
document.getElementById('theInputId').style.textTransform = 'capitalize'
}
}
</script>

Using DOM to create an input

I currently have been working on this code and I can't seem to figure it out. I am planning to make it so that if the radio button is pressed that shipping is not free, that an input field pops up to specifying what the addition cost will be using DOM. I am also trying to figure out how to add text to describe the input field, and to validate the input field.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
c++;
alert("Added Text Box");
}
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id = "tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked /> Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;"/> No
<p class="boldParagraph" id = "emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br><br>
<button>Submit</button>
</form>
</body>
</html>
Create a label element and populate text using innerHTML. and then append to DOM.
Example Snippet:
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : ";
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
c++;
alert("Added Text Box");
}
}
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button>Submit</button>
</form>
OR
You can keep the text box hidden and show it when user clicks no. Also, apply validations only when no is selected for shipment radio button.
I suggest use jQuery, see the snippet below:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
var radioButtons = $("[name=tip3]");
radioButtons.on("change", function() {
if ($("[name=tip3]:checked").val() == "3") {
$("#shipmentDetail").hide();
} else {
$("#shipmentDetail").show();
}
})
$("#submit").on("click", function() {
var flag = true;
if ($("[name=tip3]:checked").val() == "4") {
if ($("#shipmentDetail").val() == "") {
flag = false;
alert("enter some value");
}
}
//other validations here
if (flag) {
$("#form").submit()
}
})
#shipmentDetail {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="#" method="post">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" />No
<label id="shipmentDetail" for="price">Shipment Cost:
<input id="price" type="text" value="" />
</label>
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button id="submit">Submit</button>
</form>
replace
alert("Added Text Box");
with:
var additional_fees = prompt("Type in");
x.setAttribute("value", additional_fees)

How to show form fields on keyup

I've been working on this for weeks now and I can't seem to get the hang of this. I'm trying to show the hidden fields only when the previous fields are entered. Here's my example code:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1" />
<br/>
<label>Field 2:</label>
<input type="text" class="field2" />
<br/>
<label>Field 3:</label>
<input type="text" class="field3" />
<br/>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4" />
<br/>
<label>Field 5:</label>
<input type="text" class="field5" />
<br/>
<label>Field 6:</label>
<input type="text" class="field6" />
<br/>
</div>
<div id="group3">
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 9:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
</form>
CSS
#group2 {
visibility: hidden;
}
#group3 {
visibility: hidden;
}
Script
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
CheckSubmit();
});
function CheckSubmit() {
var x = true;
$('#group1').find('input[type="text"]').keyup(function () {
if ($(this).val().length === 0) {
x = false;
return;
}
});
if (x) {
$('#group2').css('visibility', 'visible');
$('#group3').css('visibility', 'visible');
} else {
$('#group2').css('visibility', 'hidden');
$('#group3').css('visibility', 'hidden');
}
CheckSubmit();
});
I'm not sure what I'm doing wrong here. Can someone please assist?
I changed your code a bit. I stored the relevant selectors in variables, so you don't need to do a lot of re-querying every time something changes.
Here's the updated code:
JavaScript
var inputs = $('#group1').find('input[type="text"]');
var hidden = $('#group2, #group3');
inputs.keyup(function() {
var test = true;
inputs.each(function(key, value) {
if (!$(this).val().length) {
test = false;
return false;
}
});
hidden.css('visibility', ( test ? 'visible' : 'hidden' ) );
});
Demo
Try before buy
You can make this more dynamic by checking the inputs in the current div and if they all have a value, then show the next div (if there is one).
If they clear a value, then hide all the later divs.
$(document).ready(function() {
// you can restrict this to inputs in a specific div or just any input
$('#group1 input').on('keyup', function () {
var parentDiv = $(this).closest('div')
var hasValues = parentDiv.find('input').filter(function() {
return this.value == '';
}).length == 0;
if(hasValues) {
//parentDiv.next().css('visibility', 'visible'); // show just the next section
parentDiv.nextAll().css('visibility', 'visible'); // show all later sections
} else {
parentDiv.nextAll().css('visibility', 'hidden');
}
});
});
DEMO
I made a quick pen with a solution. It may not be the prettiest but it get's it done. Basically on every keyup event I check #group1's children for their value length and if they all have a length that's more than 0 I change a flag in an array. If all 3 flags are true I show #group2.
Here's the pen
$('#group2').hide();
$('#group3').hide();
$('#group1').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group1 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group2').show();
}
});
$('#group2').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group2 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group3').show();
}
});
Hope it helps :D
If I understand your question well, you want to show the fields in #group2/-3 if all the fields in the previous fields have a value. Using a few data-*-attributes (see MDN), you can create a handler like this (if you prefer: jsFiddle, containing a more complete example):
$('[data-nextgroup] [type=text]').on('keyup', function (e){
var fieldgroup = $(this.getAttribute('data-group'))
,fields = fieldgroup.find('[type=text]')
,canshow = fields.length ===
fields.filter( function (i,el) { return el.value.length; } ).length;
void( canshow && $(fieldgroup.attr('data-nextgroup')).fadeIn() );
});
[data-hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="group1" data-nextgroup="#group2">
<label>Field 1:</label>
<input type="text" class="field1" data-group="#group1"/>
<br/>
<label>Field 2:</label>
<input type="text" class="field2" data-group="#group1"/>
<br/>
<label>Field 3:</label>
<input type="text" class="field3" data-group="#group1"/>
<br/>
</div>
<div id="group2" data-nextgroup="#group3" data-hidden>
<label>Field 4:</label>
<input type="text" class="field4" data-group="#group2"/>
<br/>
<label>Field 5:</label>
<input type="text" class="field5" data-group="#group2"/>
<br/>
<label>Field 6:</label>
<input type="text" class="field6" data-group="#group2"/>
<br/>
</div>
<div id="group3" data-groups data-hidden>
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 8:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>

Categories