Input field allows 6 characters when there is 5 max allowed - javascript

I have a function that removes numbers from string, it also should allow for max 5 letters to be entered. When I enter 5, and then another letter or number I can see it in console log, how can I avoid this?
document.getElementById("test").addEventListener("input", (e) => {
console.log(e.target.value);
let temp = e.target.value.replace(/[0-9]/g, '');
e.target.value = temp.substr(0, 5);
})
<input id="test" type="text">

You are loggging the value before removing the excess chars. Just move your console.log to the end of the function.
document.getElementById("test").addEventListener("input", (e) => {
let temp = e.target.value.replace(/[0-9]/g, '');
e.target.value = temp.substr(0, 5);
console.log(e.target.value);
})
<input id="test" type="text">

The problem with your code is that you are reading it from the current target that allows any number of characters, and later you are setting the substring from 0 to 5 on its value.
The simple fix would be to ask HTML to limit the number of characters so that the 6th character is never allowed.
This can be achieved by maxlength property.
<input id="test" type="text" maxlength="5">

Related

How to restrict the user to not enter more than 8 numbers?

here is my implementation
//I restrict the user to enter number only
if (isNaN(e.target.value)) {
e.target.value = e.target.value.substring(0, e.target.value.length - 1)
e.target.type = 'number'
}
// here I forced the user to enter only 8 numbers
if (e.target.value?.length > 8) {
e.target.value = e.target.value.substring(0, 8)
}
The above code works sometime sometime not. I need an alternative. is there any alternative that would be great. Thanks
You can use String's substr method, to extract only 1st 8 characters, if length of input is greater than 8.
You also need to set max="99999999" on input so that input doesn't go beyond 99999999 upon clicking <input>'s arrows.
let input = document.querySelector(".num");
input.addEventListener("input", ()=>{
if(input.value.length > 8){
input.value = input.value.substr(0,8);
}
});
<input type="number" max="99999999" class="num">
Why dont you make it simpler
<input type="number" onKeyPress="if(this.value.length==8) return false;" max="99999999"/>
type ="number" are used to let the user enter a number. They include built-in validation to reject non-numerical entries.
learn more here

Check for entering numbers only

I have a problem
I make a check when you enter upper or lower case letters in the text input to warn that letters cannot be entered but only numbers.
how to make i only enter numbers in the input?
<input type="text" id="texter">
<button onclick="checker()">
START
</button>
checker = () =>{
var texter = document.getElementById('texter').value;
if(texter.search(/[a-z]/)){
alert("letters");
return false;
}
else if(texter.search(/[A-Z]/)){
alert("letters big");
return false;
}
else{
return true;
}
}
For the best user experience, using type="number" on your input is the best bet.
<input type="number" />
If you need it to be a "text" type, one thing you can do is strip any non-numeric character from the string and set the value of the textbox to this string:
const textbox = document.querySelector('#texter');
textbox.onkeyup = event => {
const stripped = event.target.value.replace(/\D/g,'');
textbox.value = stripped;
}
<input id="texter" />
sorry but why don't just use number type of the input
<input type='number'id='texter' />
here you don't need to check for number this input just accept numbers

Perform calculation of innerHTML number input

At the moment, I display the amount of characters which are typed into a text box.
I wish to use an alternative display option and show the estimated duration. This means the inputted character amount needs dividing by 15 to give an estimated time (there is roughly 15 characters to 1 second of speech)
How can I add a math calculation to the function below?
var inputElement = document.getElementById('inputTXT');
inputElement.addEventListener('keyup', function(e) {
boxInput = e.target.value;
document.getElementById('number').innerHTML = boxInput.length;
});
You can add an extra element and use that element to calculate the result of dividing the number of characters from the input with the length method and then dividing by 15. Note I use Math.round() to round the numbers.
var inputElement = document.getElementById('inputTXT');
inputElement.addEventListener('keyup', function(e) {
boxInput = e.target.value;
document.getElementById('number').innerHTML = boxInput.length;
document.getElementById('duration').innerHTML = Math.round(boxInput.length/15);
});
<form>
<input type="text" id="inputTXT" name="firstname">
<div>
<label>characters: <label id="number">0</label></label>
</div>
<div>
<label>duration: <label id="duration">0</label></label>
</div>
</form>

Numeric value gets clear in we press letter 'e, +, -' in <input type="number">

I am having the following element defined in my code.
<input type="number"
id="phone"
required
data-length="10"
defaultValue={this.state.formValues.phone}
onInput={(e) => {
e.target.value = Math.max(0, parseInt(e.target.value)).toString().slice(0, 10)
}}
/>
The problem here is whenever I press the key 'E, +, -', the complete value in the number field gets clear. So I just wants a solution to stop this field from taking value such as 'E, +, -' and also it should not clear the value when any of the key is pressed.
The input type number works a bit different, it will let you enter characters that are not number but when you do the value of the input will be empty, a workaround is to remove the type="number" and add an if statement to check if the parsed input value is not a number, this will happen if the user inputs a letter when the input is empty, if he inputs the letter after a number the parseInt will just get the number until the letter.
You can see the working example here
document.getElementById("phone").oninput = function(e){
var inputValue = parseInt(e.target.value);
if (isNaN(inputValue)){
inputValue = 0;
}
e.target.value = Math.max(0, parseInt(inputValue)).toString().slice(0, 10)
};
<input id="phone"
required
data-length="10"
defaultValue={this.state.formValues.phone}
/>

Convert int with starting zeros to string to check length

I have an html input type="number" field in an html page. like this:
<input type="number">
To validate the form I need to check that the length of this field is exactly 3. To do this I convert the number to String and execute the length() function.
The problem comes when the number starts with a zero. like 065
In that case the toString() method outputs a 65 with a length of 2
Do you have any idea on how to get the correct length of the number ?
I think that you would have to have your input type as text and then use JavaScript to get the length for validation. After that you could convert it to a number using the Number() function.
Change the input type to text and restrict the input with a pattern and maxlength:
<input type="text" pattern="\d*" maxlength="3">
You can solve this one of two ways:
When the user moves focus away from the field, remove the leading zeroes
In the validation, remove the leading zeroes then check the length
There is no need to convert to a number.
Removing leading zeroes when focus is lost:
function truncateNumericInput(event) {
event = event || window.event;
event.target = event.target || event.srcElement;
if (event.target.nodeName != "INPUT" || event.target.type != "number") {
return;
}
var input = event.target,
value = event.target.value;
input.value = value.indexOf(".") > -1
? value.replace(/^0{2,}/, "0")
: value.replace(/^0+/, "");
}
if (document.addEventListener) {
document.addEventListener("blur", truncateNumericInput, true);
} else {
document.attachEvent("focusout", truncateNumericInput);
}
JSFiddle: http://jsfiddle.net/67jyg1d9/
Removing leading zeroes during validation
var regex = /^0+/;
var value = input.value.replace(regex, "");
console.log(value.length <= 3)
<input type="number" name="quantity" min="0" max="999">
this takes care that only number can be entered and only till 999 that's 3 digits at max
You can solve your problem by using input type as number. You can build your logic by using overflow and underflow as shown below.
<input id="numtest" type="number" min="10" max="20" />
document.getElementById('numtest').validity.rangeOverflow
document.getElementById('numtest').validity.rangeUnderflow
or
document.getElementById('numtest').checkValidity();
rangeUnderflow: return true if value is less then min
rangeOverflow: return true if value is greater than max value.

Categories