How to limit digit number in vue input? - javascript

My goal is to limit the number of digit user can enter in the input field. So a user can only input 10 digits. I tried min and max still doesn't work
Here's the code
<input
v-model="amount"
type="number"
>
<script>
export default {
data() {
return {
amount: 7800
}
}
}
</script>
Right now i can add more than 10 digits

Replace this:
<input v-model="amount" type="number">
to
<input v-model="amount"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "10"
/>

We can control the value of <input> manually:
<input
type="number"
:value="amount"
#input="updateValue"
/>
and check in updateValue method:
data() {
return {
amount: 7800
}
},
methods: {
updateValue(event) {
const value = event.target.value
console.log(value, this.amount)
if (String(value).length <= 10) {
this.amount = value
}
this.$forceUpdate()
}
}
Note that this.$forceUpdate() is used to make component re-render when user input more than 10 characters.
Demo on Codepen

Put a condition on Updated, checking the digits, if surpasses it, cut it. I did something similar, but for max value, not digits, but i think its the same logic:
updated() {
if (this.album.max_colorized > this.maxPictures) {
this.album.max_colorized = this.maxPictures;
}
}
This way if it surpasses the max, change to max.

Related

How to set decimal input range using javascript or html?

I have an input and I need it to be limited to only these values:
Min: 0.01 max 999.99
If I use maxlength="6" I can enter, for instance, 999.99 but also 1000.1 which is not an accepted value.
What I've tried:
1st attempt (not working):
<input type="number" id="quantity" name="quantity" maxlength="6" min="0.01" max="999.99">
2nd attempt (partially working):
let maximumFractionDigits = 2;
const formatNumber = (value) => {
return parseFloat(value.replace(/,/g,'')).toLocaleString('en-US', { maximumFractionDigits });
}
$('input[name="test"]').on('keyup',function(){
maximumFractionDigits = 2;
if (!$(this).val() || (maximumFractionDigits && $(this).val().endsWith('.'))) {
return
}
$(this).val(formatNumber($(this).val()).replace(/,/g,''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
INPUT TEST
<input type="text" maxlength="6" name="test" class="form-control">
<br>
With the second approach, I still can input weird numbers like 10000. and values like 0.0X can't be introduced (I guess it's rounded), how could I just limit the values to Min: 0.01 max 999.99?
You can check for 3 conditions,
For first 2 convert number to string
The max length of the string should be 6
maxlength = 6
If string has decimal point then .split('.') and check the length of decimal numbers
const decimal = input.split('.')[1]
Check if the number is
0.01 < number < 999.99
You have to methods to achieve the same
change the input type, and set min-max values:
<input type="number" min=0.01 max=999.99 name="test" class="form-control" aria-label="Equipment Procurement %">
If you don't want to change the type:
const numInput = document.querySelector(".form-control");
numInput.addEventListener("input", (event) => {
const number = parseInt(e.target.value);
if (number > 999.99 && number < 0.01) // throw Error or do whatever you want to do
})
So basically I found a solution:
const input = document.querySelector('.example');
input.addEventListener('input', updateValue);
function updateValue(e) {
let number = e.target.value;
number = number.toString();
if(number.match(/^\d{1,3}(\.\d{1,2})?$/)){
console.log("True");
} else{
const newNum = (e.target.value).toString().slice(0, -1)
e.target.value = parseFloat(newNum);
}
}
<input type="number" class="form-control example" id="quantity" name="quantity" maxlength="6" min=0.01 max=999.99>
Hope this helps if someone has the same situation

jQuery automatically move to next input with max reach value

I would like to do move to the next input with last value. For example I want to enter credit card number and each number have max 4 digit capacity if digit is more then 4 then it'll automatically move to the next input with last added value.
For example I want to add 12345 so here 1234 will add in first input and 5 will automatically move to the next input.
1234 5
I have tried using following way , automatically move to next filed is work but not move last value.
$("#card3").bind("keypress", function (e) {
var error = [];
var card3 =$("#card3").val();
if ( card3.length > 3 ) {
error.push('<p>Allow digits only(0 - 4).</p>');
if (this.value.length == this.maxLength) {
$('#card4').focus();
}
}
I am going to add 12345 so 5 automatically move to the next input.
Modifying the dupe https://stackoverflow.com/a/40221557/295783 to handle paste
If you do not NEED to handle paste, then the dupe will work for you since you cannot enter the numbers without the number after the max going to the next field
Test the below by pasting in 16 digits in the first field OR type one digit at a time
$("[data-max]").eq(0).on("input", function() {
const val = this.value;
if (val.length === 16) {
const re = new RegExp(`.{${4}}`, "g")
const chunks = val.match(re)
chunks.forEach((chunk, i) => $("[data-max]").eq(i).val(chunk))
}
})
$("[data-max]").on("input", function() {
if (this.value.length >= this.dataset.max) {
if (this.nextElementSibling) this.nextElementSibling.focus();
}
})
$("[data-max]").last().on("input", function() {
this.value = this.value.slice(0, 4)
})
[data-max] {
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" data-max="4" />
<input type="text" data-max="4" />
<input type="text" data-max="4" />
<input type="text" data-max="4" />
Here is where the problem is
if (this.value.length == this.maxLength) {
$('#card4').focus();
}
this.maxLength returns undefined therefore the block is never run.
Try
if (this.value.length == 4) {
$('#card4').focus();
}
You might want to add and retrieve maxLength value from input attribute
<input data-max-length="4" />
if (this.value.length == $(this).data('max-length')) {
$('#card4').focus();
}

Restrict a textbox to only integers between 1 and 99

I am trying to add a text box which accepts only integers between 1 and 99. I tried adding a number type element with min and max but that works only when changing the number using the ticker
<input type="number" min="1" max="99" />
May I know a better way to achieve this?
UPDATE:
I would like to immediately validate the input like may be by replacing the entry with an empty character.
You can use JavaScript to validate the input on a key event (such as keyup). Here's an example that will clear out anything that's not an integer between 1 and 99.
var inputBox = document.getElementById('inputBox');
inputBox.addEventListener('keyup', function(e) {
inputBox.value = "" + inputBox.value;
if (e.which < 48 || e.which > 57) {
// if not an integer
clearInput();
return;
}
if (inputBox.value.toLowerCase() !== inputBox.value.toUpperCase()) {
// if a letter
clearInput();
return;
}
if (parseInt(inputBox.value) < 1 || parseInt(inputBox.value) > 99) {
// if value is not in the desired range
clearInput();
return;
}
});
function clearInput() {
// invalid entry -- clear out input box
inputBox.value = "";
}
inputBox.focus(); // this is just for ease of testing
<input id="inputBox" type="number" min="1" max="99" />
How about this? This shouldn't allow for negative numbers, and you're restricted to only 2 characters.
<input type="number" min="1" max="99" maxlength="2" />

Replace part of input value on keypress jquery?

For example I have, input type with predefined length.
I want to achieve, when the input value is bigger or equal to 3, to replace that part of string[3] with '/';
<input type="text" id="number" maxlength="6" placeholder="MM/YY"/>
And here is jquery
$('#number').on('keypress',function(){
if(this.value.length <= 3) {
this.value.replace(this.value[3],'/');
}
});
So in short when user types inside input field for example: 1234, the number 3 needs to be replaced with '/' and than the value would be 12/2017, like expiration date of credit card. Thanks in advance
You can try something like this. Had to change the maximum length of input's value from 6 to 7.
Try with e.g. 12/2017.
$('#number').on('keypress', function() {
if (this.value.length >= 2) {
this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" />
You could try the following.
Where delimeterIndeces is where in the string you want to check and change the values. InputString is the string returned from the input tag.
let delimeterIndices = [2,5]; // "02[/]15[/]2017";
let inputString = "123152017";
let resultString = inputString.split('').map((char, index) => {
if(delimeterIndices.indexOf(index) !== -1) {
return '/';
} else {
return char;
}
}).join('');
console.log(resultString);

Number input field exclude range of numbers in middle

In input field how can i exclude range of numbers
e.g. allow user to put value < -5 or value > 5 and not allow anything between -4 to 4?. I am not asking for max or min values
<input type="number" id="input" step="1" />
Thanks
First add excmin and excmax attribute to target element(in this case element with id="input") to values you want.
Then call this function and pass element to this function on page load:
:
function exceptionrange(element)
{
var excmin=parseInt(element.getAttribute("excmin"))-1;
var excmax=parseInt(element.getAttribute("excmax"))+1;
element.onchange=function()
{
if(element.value<excmax&&element.value>excmin)
{
element.value=Math.round((parseInt(element.value)-excmin)/(excmin-excmax))*(excmin-excmax)+excmin;
}
};
}
Now, whenever user enter a value in this range, it will change it to near allowed value when user is done entering number.
So this is how script will look like:
function exceptionrange(element)
{
var excmin=parseInt(element.getAttribute("excmin"))-1;
var excmax=parseInt(element.getAttribute("excmax"))+1;
element.onchange=function()
{
if(element.value<excmax&&element.value>excmin)
{
element.value=Math.round((parseInt(element.value)-excmin)/(excmin-excmax))*(excmin-excmax)+excmin;
}
};
}
window.addEventListener("load",function()
{
var input=document.getElementById("input");
exceptionrange(input);
});
And this is the input element:
<input type="number" id="input" step="1" excmin="-4" excmax="4"/>
I wanted to exclude 2,4,5,7,8,9,10,11 from my Shopify products quantity in input number field so I created the following code for it.
Input Element
<input type="number" id="input"/>
JS code
function exceptionrange(element)
{
var inputValue = 0
element.onchange=function()
{
if(inputValue<element.value){
if(element.value==2)
{
element.value=3;
}
if(element.value==4 || element.value==5)
{
element.value=6;
}
if(element.value==7 || element.value==8 || element.value==9 || element.value==10 || element.value==11)
{
element.value= 12;
}
}
if(inputValue>element.value){
if(element.value==2)
{
element.value=1;
}
if(element.value==4 || element.value==5)
{
element.value=3;
}
if(element.value==7 || element.value==8 || element.value==9 || element.value==10 || element.value==11)
{
element.value= 6;
}
}
inputValue = element.value
};
}
window.addEventListener("load",function()
{
var input=document.getElementById("input");
exceptionrange(input);
});

Categories