jQuery automatically move to next input with max reach value - javascript

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();
}

Related

How to limit digit number in vue input?

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.

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" />

Getting function to run as user types

I have a phone number input that I am trying to get the dashes to appear in the number as the user types.
I am wanting the number to appear as 555-555-5555.
The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.
Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?
$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>
I modified your code slightly to produce something that I think is a little easier to read, but still does the job.
I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:
--UPDATE--
After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:
First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.
I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.
let formatFlag = false;
$(function(){
$('#phone').keyup(function(evt) {
let modifiedValue = $(this).val().replace(/-/g, "");
if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {
//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {
formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
} else {
return false; //Hyphen already present, no formatting necessary
}
} else {
formatFlag = false;
}
return false; //Return if backspace or delete is pressed to avoid awkward formatting
}
if(!!formatFlag) {
// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));
formatFlag = false; //Reset the formatFlag
}
if(modifiedValue.length % 3 == 0) {
if(modifiedValue.length === 0 || modifiedValue.length >= 9){
return false;
} else {
$(this).val($(this).val() + '-');
return;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>

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);

How to set the minimum number of words written in a text box?

I want to set a minimum number of text that is written in a text box.
Normally we use the min property of html. But I don't want it.
Can anybody help me with the JavaScript code which check the number of text written in a text box and if it is lesser than 7 and greater than 21 an alert box would be shown. Or else it wont
<input type="text" id="txt">
<input type="button" onClick="myFunction()">
Js
function myFunction() {
.....
}
I know only this much.
Please help
You can use pattern attribute of HTML5
This will set minimum characters required to 1 and max characters required
to 15
<input type="text" id="txt" pattern="[a-z]{1,15}>
function myFunction() {
if ($('#txt').val().length < 21 && $('#txt').val().length > 7) alert("yez");
}
$('button').on('click', function() {
myFunction()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt">
<button>click</button>
this should work - it checks the length of the content in your #txt HTML element. If its greater than 7 and smaller than 21 it will alert yez
i added snippet which is counting only number of real 'words' empty spaces are omitted.
function wordCount(text) {
totalCount = 0;
words = text.split(' ')
words.forEach(function(word) {
if (word.length > 0) {
totalCount++;
}
})
return totalCount;
}
window.myFunction = function() {
textarea = document.getElementById('txt');
words = wordCount(textarea.value);
if(words < 7 || words > 21) {
alert('Wrong number of words');
}
}
<input type="text" id="txt">
<input type="button" onClick="myFunction()" value="Submit">
You can trigger an event on blur that means, when the text box loses focus
$(document).ready(function(){
$('#text-box').blur(function(){
var value = $('#text-box').val();
if(value.length < 7 || value.length > 21){
alert("Invalid length");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text-box">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}

Categories