How do next input box does have value on focus - javascript

I have 4 input boxes and there is common key down function:
$(".pincode-input-text").keydown(function(e) {
if($(this).val()=="") {
$(this).attr('type','number');
} else if($(this).val()!="") {
$(this).attr('type','password');
}
// check if input is numeric
var enteredValue = e.key;
if ($.isNumeric(enteredValue)) {
$(this).val(enteredValue);
$(this).next().attr('type', 'number');
$(this).next().focus();
$(this).next().val('');
$('.fn-mtd_pin_validate').nextAll('span:first').html(" ");
} else if(!$.isNumeric(enteredValue)) {
// check if input is non numeric
$(this).val('');
if(e.keyCode == 8 || e.key == "Backspace") {
$(this).prev().focus();
var elemt = new mtdMobilePin($(window.pinvalidateElemnt).attr('id'));
elemt.validate();
return false;
}
$(this).focus();
$('.fn-mtd_pin_validate').nextAll('span:first').html("Invalid Characters");
$('.fn-mtd_pin_validate').nextAll('span:first').show();
}
// Update the value of input type password after value change on any input type.
var elemt = new mtdMobilePin($(window.pinvalidateElemnt).attr('id'));
elemt.validate();
});
<span class="fn-mtd_pin_validate">
<input type="password" min="0" step="1" maxlength="1" autocomplete="off" class="form-control pincode-input-text first mtd_pin_first" tabindex="30">
<input type="password" maxlength="1" autocomplete="off" min="0" step="1" class="form-control pincode-input-text second mtd_pin_second" tabindex="31">
<input type="password" maxlength="1" autocomplete="off" min="0" step="1" class="form-control pincode-input-text third mtd_pin_third" tabindex="32">
<input type="password" maxlength="1" autocomplete="off" min="0" step="1" class="form-control pincode-input-text fourth mtd_pin_fourth" tabindex="33">
</span>
I am unable to understand, why there is value appeared on second box as soon as value entered on first one. However I am using $(this).next().val('');

The problem here is your logic on focus needs to occur on the keyup event, not the keydown event. When the keydown event occurs you move the focus before it has finished so the keypress event is finishing after you move it. So the only way around it is to do the focus logic after the key event is done.
$(".pincode-input-text").on("keydown", function(e) {
//backspace logic
}).on("keyup", function(e) {
//number logic
})

Related

onchange event listener doesn't work when single digit numbers are appended to the value in input field[type=number]

I have two input fields, both of them have onchange event listener added to them:
HTML
<input type="number" size=5 style="width:80px;" id="funit" autocomplete="off" required>
<input type="number" size=5 style="width:80px;" id="tunit" autocomplete="off" required>
JAVASCRIPT
document.getElementById("funit").addEventListener("change",f1);
document.getElementById("tunit").addEventListener("change",f1);
function f1(){
var funit=document.getElementById("funit").value;
var tunit=document.getElementById("tunit").value;
if(funit.toString()!="" && tunit.toString()!=""){
if(funit>tunit){
alert("incorrect units");
document.getElementById("funit").value="";
document.getElementById("tunit").value="";
}
}
}
Now I have another function which fetches the values from a row of a table and inserts them into the fields. Like for example:
funit=6;
tunit=7;
Now if I add a 0 along with the input in funit, i.e., if I make it 60, then it should trigger the onchange listener, but it doesn't. Only when I erase both the input fields, and then type again, does the event listener get triggered. Why so? How do I fix this?
document.getElementById("funit").addEventListener("change",f1);
document.getElementById("tunit").addEventListener("change",f1);
function f1(){
var funit=document.getElementById("funit")
var tunit=document.getElementById("tunit")
if(funit.value && tunit.value){
if(Number(funit.value)>Number(tunit.value)){
alert("incorrect units");
funit.value="";
tunit.value="";
}
}
}
<input type="number" size=5 style="width:80px;" id="funit" autocomplete="off" required>
<input type="number" size=5 style="width:80px;" id="tunit" autocomplete="off" required>

focus function working in console but in through the code

I am trying to create a webpage which allows you to enter an IP address(IPv4). I want that whenever user has added 3 numbers in the textbox the focus should automatically be transferred to the next textbox. For that I have given onkeypress event to the textbox and called a JS function and sent an argument to it. Have a look at my code.
<input onkeypress="check(this)" type="text"
id="<?php if($i==1){echo "5";} else {echo "1";} ?>"
class="form-control" placeholder="First Octate"/>
Here is the check function
function check(element){
if(element.value.length==2){
newId= parseInt(element.id) + 1
document.getElementById(newId.toString()).focus()
}
}
Now if I log the document.getElementById(newId.toString()) to the console, it is giving me a valid element and if I use focus method with the logged element I am actually able to change the focus. What I can't understand is it is not doing the same thing if done using this function. I am not able to change the focus according to the condition
Problem with your code is the focus is not moving because of the action it takes. You need to add a slight delay
function check(element) {
if (element.value.length == 2) {
var newId = parseInt(element.id) + 1
setTimeout(()=>document.getElementById(newId.toString()).focus(),1);
}
}
<input onkeypress="check(this)" type="text" id="1" />
<input onkeypress="check(this)" type="text" id="2" />
<input type="text" id="3" />
You would be better off with keyup event
function check(element) {
if (element.value.length == 3) {
var newId = parseInt(element.id) + 1
document.getElementById(newId.toString()).focus();
}
}
<input onkeyup="check(this)" type="text" id="1" />
<input onkeyup="check(this)" type="text" id="2" />
<input type="text" id="3" />
Now this code is fine if they are typing, if they paste in a value, you have a whole new problem to solve.
Try adding a setTimeout command to your code:
function check(element){
if(element.value.length==2){
newId= parseInt(element.id) + 1
setTimeout(function() {
document.getElementById(newId.toString()).focus()
});
}
}
<input onkeydown="check(this)" type="text"
id="1"
class="form-control" placeholder="First octet"/>
<input onkeydown="check(this)" type="text"
id="2"
class="form-control" placeholder="Second octet"/>
<input onkeydown="check(this)" type="text"
id="3"
class="form-control" placeholder="Third octet"/>
<input onkeydown="check(this)" type="text"
id="4"
class="form-control" placeholder="Fourth octet"/>
Key events seem to refocus their targets' inputs after they have been fired. This tries to resolve that by waiting until the event has finished being fired, from which it will then focus the next input.
Also, I suggest you use keydown instead of keypress — the latter is deprecated.
You can set your events up in a window.load script and use data-attributes to inform your input listener on how many numbers to listen for. Also, if you use type='number' you can ensure you'll get numbers
window.addEventListener('DOMContentLoaded', () => {
let q = document.querySelectorAll('.autofoc');
q.forEach(el => {
el.addEventListener('input', e => {
let l = +e.target.dataset.len
if (e.target.value.length >= l) {
e.target.value = e.target.value.slice(0, l)
e.target.nextElementSibling.focus()
}
})
})
})
<input type="number" data-len='3' class="form-control autofoc" placeholder="Area code" />
<input type="number" data-len='3' class="form-control autofoc" placeholder="First 3" />
<input type="number" data-len='4' class="form-control autofoc" placeholder="Last 4" />

number in input field not higher than other input field

I have two input fields in my contact form, in both fields it's only possible to fill in a number. My question is, is there a way that the number in field 1 can never be higher than the number in field 2?
I have looked everywhere but can't find a solution. Is this even possible (with Javascript)? Hopefully somebody has a solution or can send me in the right direction.
<form>
<input type="number" class="fieldone" min="0" max="16" step="0.1">
<input type="number" class="fieldtwo" min="0" max="16" step="0.1">
</form>
function forceLimit(e) {
var limit = e.target.getAttribute("max");
if(e.target.value > limit)
e.target.value = limit;
}
function handleLimitChange(e) {
var limit = e.target.value;
var fieldOne = document.querySelector('#field-one');
if(fieldOne.value > limit) {
fieldOne.value = limit;
}
fieldOne.setAttribute('max', limit);
}
<form>
<input type="number" id="field-one" class="fieldone" onchange="forceLimit(event)" min="0" max="16" step="0.1">
<input type="number" id="field-two" class="fieldtwo" onchange="handleLimitChange(event)" min="0" max="16" step="0.1">
</form>
You can use jQuery to check that always the value in field 2 is greater or equal to field 1:
$('.fieldone').change(function(){
checkValue();
});
$('.fieldtwo').change(function(){
checkValue();
});
function checkValue(){
var maxValue = $('.fieldtwo').val();
if(maxValue > 0 && $('.fieldone').val() > maxValue){
$('.fieldone').val(maxValue);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="number" class="fieldone" min="0" max="16" step="0.1">
<input type="number" class="fieldtwo" min="0" max="16" step="0.1">
</form>

How to display input as bullet marks in input number element?

My user is required to input 5 digit number for a pass code. Once the number is entered in to the input number field the number should not be shown. It should be changed to a black color bullet. How do I achieve that?
Here is my html:
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input{
text-align:center;
}
<div class="creditCardNumber">
<input type="number" name="" min="0" max="9" maxlength="1" step="1" onKeyPress="if(this.value.length==1) return false;">
<input type="number" name="" min="0" max="9" maxlength="1" step="1" onKeyPress="if(this.value.length==1) return false;">
<input type="number" name="" min="0" max="9" maxlength="1" step="1" onKeyPress="if(this.value.length==1) return false;">
<input type="number" name="" min="0" max="9" maxlength="1" step="1" onKeyPress="if(this.value.length==1) return false;">
<input type="number" name="" min="0" max="9" maxlength="1" step="1" onKeyPress="if(this.value.length==1) return false;">
</div>
Looking the result like this:
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input{
text-align:center;
width: 10%;
//Set the width of the inputs so changing the input type won't affect it.
}
//Go get those inputs -> returns an HTMLCollection
const inputs = document.getElementsByTagName("input");
//Let's turn that HTMLCollection into an array won't we?
const inputArray = Array.from(inputs);
//Ok now let's set up an array to store the user's password. This array has a length of "inputArray.length", so if you add more inputs, the array will grow accordingly.
let passwordArray = new Array(inputArray.length);
//Let's loop through the input. Oh yeah, let's pass the index also!
inputArray.forEach((input, index) => {
//Ok now on "blur" event, we want to save the value of the input if existant.
input.addEventListener("blur", () => {
if(input.value.length !== 0) {
//Get that value into that passwordArray.
passwordArray.splice(index, 1, input.value);
//Now for the trickery, let's change that input type back to password. So we can have that bullet.
input.type = "password";
}
});
//Alternatively, if the user wants to go back and change an input, let's change it back to input type number.
input.addEventListener("focus", () => {
input.addEventListener("focusin", () => {
input.type = "number";
input.value = "";
});
});
});
///////////////////////////////////////////////////////////////////////////////
///// Here's the non ES6 version if you're more comfortable with that ////////
/////////////////////////////////////////////////////////////////////////////
//Go get those inputs -> returns an HTMLCollection
var inputs = document.getElementsByTagName("input");
//Let's turn that HTMLCollection into an array won't we?
var inputArray = Array.from(inputs);
//Ok now let's set up an array to store the user's password. This array has a length of "inputArray.length", so if you add more inputs, the array will grow accordingly.
var passwordArray = new Array(inputArray.length);
//Let's loop through the input. Oh yeah, let's pass the index also!
inputArray.forEach(function (input, index) {
//Ok now on "blur" event, we want to save the value of the input if existant.
input.addEventListener("blur", function() {
if(input.value.length !== 0) {
//Get that value into that passwordArray.
passwordArray.splice(index, 1, input.value);
//Now for the trickery, let's change that input type back to password. So we can have that bullet.
input.type = "password";
}
});
//Alternatively, if the user wants to go back and change an input, let's change it back to input type number.
input.addEventListener("focusin", () => {
input.type = "number";
input.value = "";
});
});
https://fiddle.jshell.net/4xghnybf/7/
I use this approach this is much better:
<input type="number" pattern="[0-9]*" inputmode="numeric" min="0" max="9" style="-webkit-text-security: disc;" autofocus />

Add placeholder instead of value in number and range input when value is 0 - Angular.js

I have a number and range input that are working in unison using same value using Angular.js value. When the value is set to 0 (which is what it is by default when page loads $scope.lbs_needed = 0;, I want to show a placeholder="0" whenever the value of the number or range input is set to 0 that way the 0 value isn't in front of the user's input without them having to manually delete default 0.
Here's my html:
<form>
<div class="form-group">
<label for="number">Pounds of nitrogen desired per acre:</label>
<input type="number" class="form-control number-input" id="number" ng-model="lbs_needed" ng-change="calculate2()" value="{[{lbs_needed}]}" min="0" max="500" value="{[{lbs_needed}]}" placeholder="0">
<input type="range" min="0" max="500" class="form-control" id="number" ng-model="lbs_needed" ng-change="calculate2()" value="{[{lbs_needed}]}" placeholder="0">
</div>
</form>
So, if I understand correctly you want the textbox to have a default value but also want it to be changeable instantly without users having to backspace over the default?
Try this:
var input = document.getElementById('change-default');
input.onfocus = function () {
if (input.value == 0) {
input.value = '';
}
}
input.onblur = function () {
if (input.value == '') {
input.value = '0';
}
}
<input type="number" placeholder="0" value="0" id="change-default">
What I'm doing is listening for an focus event, you could also use addEventListener instead of onfocus.
If the value of the input box is 0 you remove its value ready for the user to type theirs in.

Categories

Resources