Verify input value - javascript

I'm trying to read a value from an input an verify if it's a certain number of my choosing. What I've got so far is:
const input = document.getElementById('input');
var val = parseInt(input.value);
input.addEventListener('input', () => {
if(val == 1){
alert('test')
}
})
<input id="input">
But it doesn't work as intented. There is barely any code here so the solution must be simple but I can't find it, any help would be appreciated.

Put,
const input = document.getElementById('input');
var val = parseInt(input.value);
inside the listener like below
input.addEventListener('input', () => {
const input = document.getElementById('input');
var val = parseInt(input.value);
if(val == 1){
alert('test')
}
})
<input id="input">

Try using a type attribute in your input.
<input type="number" id="input" />
And in your JavaScript, use input.innerHTML instead of input.value, that way it returns the most updated value.
And 'input' is not a JavaScript Event.
input.addEventListener('oninput', function () {});
//Or, The Way I Would Prefer:
input.addEventListener('onchange', function () {});

Related

How to set default input for input keypress?

I have a webpage written in React (but it should not be strictly relevant to that question) that is composed by several inputs, let's call them Name, Surname and Code.
To work quickly, the insertion of the code is done with a Barcode Scanner that works as external keyboard. My idea is that if some field is focused, the keypress is inserted in the focused input but, in case no input is focused, I want to automatically focus and fill the Code input.
Is there a way to that it easily?
let inputName = document.querySelector('input[name="name"]');
let inputSurname = document.querySelector('input[name="surname"]');
let inputCode = document.querySelector('input[name="code"]');
let focusedInput = null;
[inputName, inputSurname, inputCode].forEach((input) => {
input.addEventListener('blur', () => {
focusedInput = null;
});
input.addEventListener('focus', () => {
focusedInput = input;
});
});
document.body.addEventListener('keypress', () => {
if (focusedInput == null) {
inputCode.focus();
}
});
<div>
<label>Name</label>
<input type="text" name="name" />
</div>
<div>
<label>Surname</label>
<input type="text" name="surname" />
</div>
<div>
<label>Code</label>
<input type="text" name="code" />
</div>
const surnameInput = document.getElementById('surname-input');
... (= do for all inputs)
let activeInput;
surnameInput.onFocus = () => { activeInput = surnameInput };
...
surnameInput.OnBlur = () => { activeInput = undefined };
...
document.addEventListener('keypress', (ev) => {
const input = activeInput ?? codeInput;
input.value += valueOftheKey;
}
You'd obviously have to evaluate if the key that was pressed has a value which you can add to the input, but I think this should give you an Idea of what to do. I haven't tried it out though, so it might not completely work.
Also: I'm not sure if it's the most efficient way, but it's an option.
EDIT: Answer by Kostas is better ;) except for the null...you should use undefined

How to query multiple elements that start with the same ID and then check whether the input has changed

I have a list of text inputs which all start with the same id but are slightly different at the end. When text is entered by the user in any of these input fields I want to execute a function. At the moment this is working with the following code:
var heightInches = document.querySelector("#Height_Inches");
var heightFeet = document.querySelector("#Height_Feet");
var heightCentimeters = document.querySelector("#Height_Centimeters");
heightInches.oninput = function (e) {
console.log("Edited");
}
heightFeet.oninput = function (e) {
console.log("Edited");
}
heightCentimeters.oninput = function (e) {
console.log("Edited")
}
The issue is that I don't like the repetition and would rather query all of the ids that begin with "Height_" and do something (as what is excuted inside each function will be the same.
Here is what I have tried but does not work:
var allHeight = document.querySelector('[id*="Height_"]');
allHeight.oninput = function (e) {
console.log("edited");
}
I have also tried the same with querySelectorAll
Please could someone help with where I am going wrong here? Every other Stack Overflow answer and article I see seems to suggest that id* is the correct way to select? Thank you
If I understand correctly, this is what you are looking for.
The only thing you were missing is looping through your elements.
const inputs = document.querySelectorAll('[id*="Height_"]');
inputs.forEach( input => {
input.oninput = function (e) {
console.log("edited");
}
})
<input type="text" id="Height_1">
<input type="text" id="Height_2">
<input type="text" id="Height_3">
Rather than use an ID, which is intended to be unique, why not add a class like .height-input to each input and then you can select them all?
// Get elements
const inputs = document.querySelectorAll('.height-input');
const outputEl = document.querySelector('.output');
// Attach event handlers
for (let i = 0; i < inputs.length; i++) {
inputs[i].oninput = function(e) {
// Handle input
outputEl.innerHTML = `Input received on #${e.target.id}`;
}
}
.output {
margin-top: 10px;
}
<input type="text" class="height-input" id="HeightInches">
<input type="text" class="height-input" id="HeightFeet">
<input type="text" class="height-input" id="HeightCentimeters">
<div class="output">Waiting for input...</div>

How to detect when a user types a string in an input type number?

I have a form with an input type number. I want to display a message when the user types a string.
When I try to retrieve the value of the input, I always get an empty string.
When I type a number it works fine but not with a string...
I tried with both jQuery and javascript.
var inputVal = $(this).val();
var inputValJs = document.getElementById("myInput").value;
console.log(inputVal); // if 99 => 99 if test => ''
console.log(inputValJs); // if 99 => 99 if test => ''
How should I proceed ?
Input type number only allow you to enter numbers
var inputValJs = document.getElementById("myInput").value;
console.log(inputValJs);
<input type="number" id="myInput" name="tentacles" value ="33">
If you really need an input text you can do the following:
The event input captures the changes in the input text.
var messageElem = document.querySelector('#myMessage');
document.querySelector('#myInput').addEventListener('input', function(e) {
if (this.value === '' || /^[0-9]+$/.test(this.value)) {
messageElem.textContent = "";
} else {
messageElem.textContent = "Only numbers";
}
});
<input type="txt" id='myInput'>
<p id='myMessage'>
Number type input only accept number value.
To retrieve input value, use event listener :
var myValue = '';
document.getElementById("myInput").addEventListener('input', function(e) {
myValue = e.target.value;
console.log(myValue);
});
<input type="number" id="myInput">

Temporarily disable an input field if second input field is filled

I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">

javascript add two multipleevents on input field

I am trying to add two events on input field like onkeyup and onchange, the purpose is to avoid longpress of characters other than numbers..as the field is for zipcode. At present only one event is working either keypress/onchange.
I am adding my code for refrence any help would be appreciated.
function zipchange(obj, selector){
var code = obj.value;
var isnum = /^\d+$/.test(code);
if(!isnum)
obj.value="";
}//onchange
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
obj.value = code.substring(0,4)+'-'+substr;
}//onkeypress
//html
<input id="pincode" type="text" data-validate="validate[required]" name="address.pinCode" required="true" onkeyup="autoZip(this)" onchange="zipchange(this)" msg="Enter valid zip code" />
Answer:
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
var substr1 = code.substring(0,4);
obj.value = substr1+'-'+substr;
var isnum = /^\d+$/.test(substr1)
if(!isnum)
obj.value="";
}
Hi the above modified function did the trick..thanks for all the enlightned ones who helped me..
Well first of all onchange is triggered when you change the content of the text-box and when you loose focus from input type
Hence there is no use in using onchange event you have to implement your onchange logic in keyup event

Categories