Smart input with jQuery mask - javascript

I want to create a smart input field for phone numbers with the jQuery mask plugin.
If the focus is in the input and index #4 value = 91 input, show
$("#phone").mask("+97(912)1234567");
and if 0912 back in to 912 and remove 0 from the mask in realtime
My code:
var smart_input = setInterval(function () {
var phone = $('#phone').val();
var phone_element = $('#phone');
if (phone.indexOf('09') == 0 && phone.length != 0) {
var prefix = phone.substring(1);
$('#phone').mask('(999) 999 9999');
phone_element.val(prefix);
} else if (phone.indexOf('91') == 0 && phone.length != 0) {
var prefix = phone.substring(1);
$('#phone').mask('(999) 999 9999');
phone_element.val(prefix);
}
}, 1);

In same scenario I took this as a reference . Please try

Related

Multiple condition for phone number field in javascript

I have below code:
$('.mobileNumber').keyup(function () {
var mobile = $(this).val();
var numericExpression = /^[0-9]+$/;
if (mobile.length == 0 || mobile.length < 10 || !mobile.match(numericExpression)) {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','block');
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
}
});
what i'm trying to do is whenever my mobileNumber fields blank(ie. o length),less than 10 length and it should follow numbers only. if yes, then error message i.e. .jp-error-msg-kstm will appear else not.
for example, if i entered 1234567890 then it should not show me the error whereas if erase the value and make the field as 0 length or less than 10 then it should shoe the error span div.
Simply use .length.
if (mobile.length < 10 || !mobile.match(numericExpression)) {
I have used
mobile.length == 0
in the first if condition only.
So the code become
$('.mobileNumber').keyup(function () {
var mobile = $(this).val();
var numericExpression = /^[0-9]+$/;
if (mobile.length < 10 || !mobile.match(numericExpression)) {
if(mobile.length == 0){
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','block');
}
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
}
});

JavaScript Form Validation not working using isNaN

I have changed my code and added the isNaN to make sure a credit card validation is checking that only numbers are entered, however it broke the code.
Note this is only a code snippet of the broken code.
Tried adding backets and moving around code.
var american = document.getElementById("americanInput").value;
var master = document.getElementById("masterInput").value;
var visa = document.getElementById("visaInput").value;
var email = document.getElementById("email").value;
var errMsg = document.getElementById("errMsg");
var postcode = document.getElementById("billingPostcode").value;
var address = document.getElementById("billingAddress").value;
var suburb = document.getElementById("billingSuburb").value;
} else if (master.length > 0 && master.length !== 16 && isNaN(master)||
visa.length > 0 && visa.length !== 16 && isNaN(visa)||
american.length > 0 && american.length !== 15 && isNaN(american)){
errMsg.innerHTML = "Please check your card details again";
return false;
} else if (postcode.length < 4 || (!postcode.match(/^[0-9]*$/))) {
errMsg.innerHTML = "Please enter a valid postcode";
return false;
} else if (suburb.length < 8 || address.length < 8) {
errMsg.innerHTML = "Please check your address, to confirm details"
return false;
}
The code should validate and give an error message.
Try the below code. I have used 'OR' condition with isNaN instead of 'AND' condition. I assume you are checking for the credit card value is not null/undefined in your code. If not you need to check to make sure the below code works.
var american = document.getElementById("americanInput").value;
var master = document.getElementById("masterInput").value;
var visa = document.getElementById("visaInput").value;
var email = document.getElementById("email").value;
var errMsg = document.getElementById("errMsg");
var postcode = document.getElementById("billingPostcode").value;
var address = document.getElementById("billingAddress").value;
var suburb = document.getElementById("billingSuburb").value;
if ((master.length > 0 && (master.length !== 16 || isNaN(master))) ||
(visa.length > 0 && (visa.length !== 16 || isNaN(visa))) ||
(american.length > 0 && (american.length !== 15 || isNaN(american)))) {
alert("Please check your card details again");
return false;
} else if (postcode.length < 4 || (!postcode.match(/^[0-9]*$/))) {
alert("Please enter a valid postcode");
return false;
} else if (suburb.length < 8 || address.length < 8) {
alert("Please check your address, to confirm details");
return false;
}

Validation on textbox using jquery for pan Number format

I have to add Pan no in my website Application but i have to use jquery for validation so that first 5 no. should be alphabet then 4 no. should be numeric and the last Questions should be alphabet.
$('#txtPANNumber').keypress(function (event) {
var key = event.which;
var esc = (key == 127 || key == 8 || key == 0 || key == 46);
//alert(key);
//var nor = $("#txtPANNumber").mask("aaaaa9999a");
var regExp = /[a-zA-z]{5}\d{4}[a-zA-Z]{1}/;
var txtpan = $(this).val();
if (txtpan.length < 10 ) {
if( txtpan.match( regExp) ){
//event.preventDefault();
}
} else { event.preventDefault(); } });
Please provide some solutions
This will do
/[a-zA-z]{5}\d{4}[a-zA-Z]{1}/
Check here
Code
$('#txtPANNumber').change(function (event) {
var regExp = /[a-zA-z]{5}\d{4}[a-zA-Z]{1}/;
var txtpan = $(this).val();
if (txtpan.length == 10 ) {
if( txtpan.match(regExp) ){
alert('PAN match found');
}
else {
alert(Not a valid PAN number);
event.preventDefault();
}
}
else {
alert('Please enter 10 digits for a valid PAN number');
event.preventDefault();
}
});
You can use below regex to validate input for PAN.
[A-Z]{5}[0-9]{4}[A-Z]{1}
Function for JS :
function validatePAN(pan){
var regex = /[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
return regex.test(pan);
}
But don't rely only on JS validation, as JS validation can easily disabled from client side. Put a check on server side as well for inputs.
Also you need to change your if condition to something like below :
if(length == 10)

How to Validate Text box on depend of another Text box?

I am Performing Calculation of Student fee Details,There are Two Text boxes,one which is automatically fixed(disabled)as Rs.5000,If i enter value below Rs.5000 value on another Text box then it will calculate subtraction and show balance in result text box.If i enter value above Rs.5000 it should not take that value in second text box.I want to validate text box depending on first text box value.
Here is my body part
my script part
$(".maxmin").each(function () {
var thisJ = $(this);
var max = thisJ.attr("max") * 1;
var min = thisJ.attr("min") * 1;
var intOnly = String(thisJ.attr("intOnly")).toLowerCase() == "true";
var test = function (str) {
return str == "" || /* (!intOnly && str == ".") || */
($.isNumeric(str) && str * 1 <= max && str * 1 >= min &&
(!intOnly || str.indexOf(".") == -1) && str.match(/^0\d/) == null);
// commented out code would allow entries like ".7"
};
thisJ.keydown(function () {
var str = thisJ.val();
if (test(str)) thisJ.data("dwnval", str);
});
thisJ.keyup(function () {
var str = thisJ.val();
if (!test(str)) thisJ.val(thisJ.data("dwnval"));
})
});
You can do on textchanged something like this
$(textbox1).on('change', function () {
if(textbox1.val()==5000){
//do your code
}
else if(textbox1.val()<5000){
//do your code
}
});
Look into the onchange (https://api.jquery.com/change/) or keyup events (https://api.jquery.com/keyup/). Get the values and perform your calculations.

Jquery keydown() with number format not work correctly on android webview

I have encountered a strange behavior on android browser / webview. I was testing an input that will automatically format to phone number format "(xxx) xxx-xxxx". But then what happened was when I tapped or press any number on androids keyboard, the first input was like this "(x" but then the cursor was in between "(" and "x". Is there a way to put the cursor after "x" value?
I tested this on iPhone and windows web browsers and it works fine. Please let me know if there are mistakes on my jquery or javascripts.
Thanks
HTML CODE:
<html>
<head>
<title>Sample Phone Number Format</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<input type="text" id="phone" />
<script type="text/javascript">
$('#phone').on('keydown', function (event) {
objval = $(this).val();
if (event.keyCode == 46 || event.keyCode == 8) {} else {
if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 95 && event.keyCode < 106) || (objval.length > 13))) {
event.preventDefault();
} else {
if (objval.length == 0) {
$(this).val(objval + '(');
alert(objval + '(');
} else if (objval.length == 4) {
$(this).val(objval + ') ');
alert(objval + ') ');
} else if (objval.length == 9) {
$(this).val(objval + '-');
alert(objval + '-');
} else if (objval.length >= 14) {
if (event.keyCode == 9) {
return;
} else {
event.preventDefault();
}
}
}
}
});
$('#phone').on('keydown', function (event) {
var objVal = $(this).val();
if(objVal.length < 14)
{
validateCallerForm(objVal + String.fromCharCode((96 <= event.keyCode && event.keyCode <= 105)? event.keyCode-48 : event.keyCode));
}
});
//Validates proper phone format, true if valid phone number, false otherwise
function isValidPhoneNumber(elementValue) {
var numberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
return numberPattern.test(elementValue);
}
//validates entire caller form, also updates css classes for proper response
function validateCallerForm(PhoneNumber) {
if (isValidPhoneNumber(PhoneNumber)) {
alert("true");
} else {
alert("false");
}
}
</script>
</body>
</html>
Giving +50 Bounty to who'm will answer this correctly
you have to first define listener for typing and copy-paste like below (not required) :
$("#phone").keyup( function() {
maskLine(this);
});
$("#phone").change( function() {
maskLine(this);
});
Then, to manage cursor placement, you have to cache previous phone number and then, you could compare difference and update cursor position if needed.
So declare, you have to declare a global array like this :
var _cacheElementValues = new Array();
At last, you can check the function below, it applies your mask to phone number field and manage cursor placement :
function maskLine( element ) {
element = $(element);
var maskedLine = '';
var line = element.attr('value');
// check the cache of the input and abord if no change since last treatment
if (_cacheElementValues[element.attr('id')] != undefined && _cacheElementValues[element.attr('id')] == line) {
return;
}
line = line.replace(/\D/g, ''); // remove all characters != digits
line = line.substring(0, 10);
if (line != '') {
// apply mask
if (line.length <= 2 ) {
maskedLine = "(" + line;
} else if (line.length < 6) {
maskedLine = line.replace(/^([0-9]{3})([0-9]{0,3})/g, '($1) $2');
} else {
// mask : '(XXX) XXX-XXXX'
maskedLine = line.replace(/^([0-9]{3})([0-9]{3})([0-9]{0,4})/g, '($1) $2-$3');
}
}
// define cursor position at the end of the input by default
var pos = maskedLine.length;
// Change cursor placement if necessary
if (typeof element[0].selectionStart != 'undefined') {
var start = element[0].selectionStart;
var end = element[0].selectionEnd;
var insText = element[0].value.substring(start, end);
// get current cursor placement
if (insText.length == 0) {
pos = start;
} else {
pos = start + insText.length;
}
// find how many digits typing since last mask application
var previousLength = 0;
if (_cacheElementValues[element.attr('id')] != undefined) {
previousLength = _cacheElementValues[element.attr('id')].replace(/\s/g, '').length;
}
var diff = maskedLine.replace(/\s/g, '').length - previousLength;
// if sum of new typing digit is > 0 : we change cursor placement
if (diff > 0) {
pos += (diff - 1) + Math.round((diff-1)/3);
if (pos%6 == 0 && maskedLine.length >= pos+1) pos++;
}
}
// update input data & cache
element.val(maskedLine);
_cacheElementValues[element.attr('id')] = maskedLine;
// update cursor placement
element[0].selectionStart = element[0].selectionEnd = pos;
}
You can find this example on jsFiddle : http://jsfiddle.net/UE9LB/5/
I hope this little explantion can solve your problem ;)
Enjoy !
ps: i apologize for my poor english :s
I'd recommend at least starting with an existing plugin rather than going through your own isolated rounds of solving issues.
http://digitalbush.com/projects/masked-input-plugin/
https://github.com/igorescobar/jQuery-Mask-Plugin
The short answer is to set the selectionStart and selectionEnd properties of the input element. After you format the value, set these properties to this.value.length.
this.selectionStart = this.value.length;
this.selectionEnd = this.value.length;
But, where you are going to run into trouble is when the cursor is not at the end of the text. Eg, the user has manually positioned the cursor to a position within the text. To prevent the cursor from jumping to the end, you will need to detect the cursor position before you format the input, then put the cursor back in the appropriate position after formatting.
Edit: This jsFiddle may get you started, but isn't perfect yet.
I rewrite the code on my #phone keydown event and this will work on iPhone, Android, webkit browsers.
$('#phone').on('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
// ignore if BKSPCE, left arrow, or right arrow
} else {
// validate if anything else
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,10);
var string = ("(" + first3 + ") " + next3 + "-" + next4);
$(this).val(string);
}
});

Categories

Resources