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);
Related
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();
}
My goal is to flag when a user enters the same text into one input that matches at least one other input's text. To select all of the relevant inputs, I have this selector:
$('input:text[name="employerId"]')
but how do I select only those whose text = abc, for instance?
Here is my change() event that checks for duplicate text among all the inputs on the page. I guess I am looking for something like :contains but for text within an input.
var inputsToMonitorSelector = "input[type='text'][name='employerId']";
$(inputsToMonitorSelector).change(function() {
//console.log($(this).val());
var inputsToExamineSelector = inputsToMonitorSelector
+ ":contains('" + $(this).val() + "')";
console.log(inputsToExamineSelector);
if($(inputsToExamineSelector).length > 1) {
alert('dupe!');
}
});
Or is there no such selector? Must I somehow select all the inputsToMonitorSelector's and, in a function, examining each one's text, incrementing some local variable until it is greater than one?
With input you need to use [value="abc"] or .filter()
$(document).ready(function() {
var textInputSelector = 'input[type="text"][name="employerId"]';
$(textInputSelector).on('input', function() {
$(textInputSelector).css('background-color', '#fff');
var input = $(this).val();
var inputsWithInputValue = $(textInputSelector).filter(function() {
return this.value && input && this.value == input;
});
var foundDupe = $(inputsWithInputValue).length > 1;
if(foundDupe) {
console.log("Dupe found: " + input);
$(inputsWithInputValue).css('background-color', '#FFD4AA');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="employerId" value="abc">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
<input type="text" name="employerId" value="">
[value="abc"] means if the value is abc
[value*="abc"] * means if the value contains abc
[value^="abc"] ^ means if the value starts with abc
[value$="abc"] $ means if the value ends with abc
Note: :contains() not for inputs , and word text not used with inputs and <select>.. inputs and <select> has a value
In your case .. instead of using
$(inputsToExamineSelector).length > 1)
You may need to use .filter()
$(inputsToExamineSelector).filter('[value*="abc"]').length > 1)
OR
$('input[type="text"][name="employerId"]').filter(function(){
return this.value.indexOf('abc') > -1
// for exact value use >> return this.value == 'abc'
}).length;
And to use a variable on it you can use it like
'[value*="'+ valueHere +'"]'
Something like this works. Attach isDuplicated(myInputs,this.value) to a keyup event listener attached to each input.
var myInputs = document.querySelectorAll("input[type='text']");
function isDuplicated(elements,str){
for (var i = 0; i < myInputs.length; i++) {
if(myInputs[i].value === str){
myInputs[i].setCustomValidity('Duplicate'); //set flag on input
} else {
myInputs[i].setCustomValidity(''); //remove flag
}
}
}
Here's another one. I started with vanilla js and was going for an answer like Ron Royston with document.querySelector(x) but ended up with jquery. A first attempt at several things but here you go:
$("input[type='text']").each(function(){
// add a change event to each text-element.
$(this).change(function() {
// on change, get the current value.
var currVal = $(this).val();
// loop all text-element-siblings and compare values.
$(this).siblings("input[type='text']").each(function() {
if( currVal.localeCompare( $(this).val() ) == 0 ) {
console.log("Match!");
}
else {
console.log("No match.");
}
});
});
});
https://jsfiddle.net/xxx8we6s/
Upon clicking a submit button, I would like to do some client side validation to ensure there are fewer than 5 commas in a text box with the class of submit-btn. I can use javascript, jquery and/or regex here.
What code should I place within this function?
$('.submit-btn').on("click", function() {
<< WHAT GOES HERE? >>
});
Any help is greatly appreciated.
I use regex to find the number of times the string , occurs in the textbox value. It prints whether or not it is valid (having less than 5 commas).
$("#validate").click(function () {
console.log(($("#textboxInfo").val().match(/,/g)||[]).length < 5)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" />
<button id="validate">less than 5 commas?</button>
Automatically responding to user input
In this particular situation, I'd prefer to have live validation. This can be accomplished by using the input event.
$("#textboxInfo").on('input', function () {
var isValid = ($(this).val().match(/,/g) || []).length < 5;
$(".isValid").html(isValid ? "Valid" : "Invalid");
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textboxInfo" value="I really love ,,, commas!" />
<div class="isValid"> </div>
Split the value of the input box and filter out , and check the length of it
$('.submit-btn').on("click", function() {
var getNumbers = $('#testBox').val().split('').filter(function(item) {
return item === ','
}).length;
console.log(getNumbers)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='testBox'>
<button class='submit-btn' type="button">Click</button>
You could try using this Comma Counter
$('button').on('click',function(){
var counter = ($('div').html().match(/,/g) || []).length;
$('.result').text(counter);
}
)/
You could also remove everything that is not a comma [^,], replace that with an empty string and count the length of the string.
$('.submit-btn').on("click", function() {
var nr = $("#tbx").val().replace(/[^,]/g, "").length;
console.log("Fewer than 5 commas? " + (nr < 5 ? "Yes" : "No") + " there are " + nr + " commas.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='tbx'>
<button class='submit-btn' type="button">Click</button>
MY CODE
function validate(e, id) {
var reg = new RegExp('^\\d+$');
if (reg.test($("#" + id).val())) {
var value = $("#" + id).val();
alert(value);
} else {
alert("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="number" id="number-input" oninput="validate(event,'number-input');">
This accept 1.(dot after any digits) value rest all is good.
You can try using <input type="tel" ...>. This way when user types 1. you will receive 1. only and not 1 and it will also open number keypad on mobile.
function validate(e, id) {
var reg = /^[0-9]*(\.(?=[0-9]+))*[0-9]+$/;
var value = $("#" + id).val();
if (reg.test(value)) {
console.log(value);
} else {
console.log("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="tel" id="number-input" oninput="validate(event,'number-input');">
You can also refer to How to get the raw value an <input type="number"> field? for more information in why 1. returns 1 and not 1.
It work as fallow:
1 pass
1. fail
1.1 pass
function validate(e, id) {
var value = $("#" + id).val() + "";
if (new RegExp('^[0-9]+\.[0-9]+$').test(value)
|| ((new RegExp('^[0-9]+').test(value) && !value.includes(".")))
) {
var value = $("#" + id).val();
alert($("#" + id).val() + "->" + value);
} else {
alert("fail " + $("#" + id).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="text" id="text-input" oninput="validate(event,'text-input');">
Here is a code that might help you.In the below code when the user types . it is replaced by null.It only accepts digits.This is for input type="text".The variable currValue has the value of the input.
The search() method searches a string for a specified value, and returns the position of the match.The search value can be string or a regular expression.This method returns -1 if no match is found.
Then I am using .replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Here I am replacing it with null if the regex doesn't match.The regex [^0-9] checks if not digit.
JSFIDDLE
Here is the code:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label>Digits Only:
<input type="text" />
</label>
<br>
<br>
EDIT :
In input type="number" we have to force it to always accept the updated val since many events does not work in it.So for that reason I have to update the existing value with the updated value after each event.
So I added
var v = $(this).val();
$(this).focus().val("").val(v);
So that each time the input is focused the value get updated with the existing value.
UPDATED FIDDLE FOR INPUT TYPE NUMBER
Updated snippet:
$(function() {
$('input').bind('keyup input', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" />
</label>
<br>
<br>
EDIT 2 : For special case + and -.I think its a bug I am not sure but check the below snippet.It works for all the cases.Hope it helps.
FINAL FIDDLE
$(function() {
$('input').bind('keyup', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
$(this).val(currValue.replace(/[^0-9]/, ''));
alert(v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;">
</label>
<br>
<br>
Hope it helps.For any other doubt feel free to ask.
I have the following html form fields that I need the sum of acct1, acct2 and acct3 to equal the value of the surcharge field.
<input type="text" name="surcharge" id="surcharge" class="gui-input" placeholder="xx.xx">
<input type="text" name="acct1" id="acct1" placeholder="xx.xx">
<input type="text" name="acct2" id="acct2" placeholder="xx.xx">
<input type="text" name="acct3" id="acct3" placeholder="xx.xx">
I have tried several variations of this thus far:
$('#surcharge').change(function(){
if( ( $('#acct1').val() + $('#acct2').val() + $('#acct3').val() ) == $('#surcharge') ){
alert("Values match Surcharge");
}
else {
alert("Values DO NOT match Surcharge");
}
});
The problem is that the val() method returns a string. It needs to be converted to an integer first. You can do that by calling Number() and wrapping the value inside the parentheses.
$('#surcharge').change(function(){
if( Number($('#acct1').val()) + Number($('#acct2').val()) + Number($('#acct3').val()) == $('#surcharge').val() ){
alert("Values match Surcharge");
}
else {
alert("Values DO NOT match Surcharge");
}
});
This is kind of tough to read though, so might be a better idea to break it down
$('#surcharge').change(function() {
var total = 0;
$("#acct1", "#acct2", "#acct3").each(function() {
total += Number($(this).val());
});
if (total == $('surcharge').val()) {
});
Try to cast the value to integer
parseInt($('#acct1').val())+parseInt($('#acct2').val());
You need to convert you field values to numbers. The default input field value is a string. At the moment you are adding strings. To get a number do this for all your fields (including surcharge):
parseFloat($('#acct1').val());
$('#surcharge,#acct1,#acct2,#acct3').keyup(function() {
console.log([parseInt($('#acct1').val()),parseInt($('#acct2').val()),parseInt($('#acct3').val()), parseInt($('#surcharge').val())]);
if (
(
parseInt($('#acct1').val()) + parseInt($('#acct2').val()) + parseInt($('#acct3').val())
) == parseInt(
$('#surcharge').val()
)
) {
alert("Values match Surcharge");
} else {
alert("Values DO NOT match Surcharge");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="acct1" value="1">+
<input id="acct2" value="1">+
<input id="acct3" value="1">=
<input id="surcharge" value="3">
You should change your listener to something like blur so the event doesn't trigger with every change (key press) on the surcharge field.
Also, add a class to all of your acct input fields so you can loop by the class:
$( "#surcharge" ).blur(function() {
var total = 0;
$(".acct").each(function() {
if($(this).val()) {
total += parseFloat($(this).val());
}
});
//you may want total.toFixed(2)
if(parseFloat($(this).val()) == total.toFixed(2)) {
alert("Values match Surcharge");
} else {
alert("boooo!");
}
});
And here's a JSFiddle demo.