(XXX) XXX-XXXX xXXXX
I want insert a X symbol after every 15th character in input. I have a Business Phone input box. When a user is typing and reaches each 15th character, then jQuery will insert a hyphen (X).
For example: (999) 999-9999 x9999
I'm trying some codes and i think i'm so close to correct code but i have some problems. Here is my code sample;
$(document).delegate('#businessPhone', 'keyup', function(e) {
var Textlength = $(this).val();
console.log(Textlength.length);
if (Textlength.length >= 14) {
//alert("if"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999 x9999");
return false;
} else {
//alert("else"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999");
}
});
Code is working fine as aspected if user complete enter all characters.
But problem is user wants to remove characters the characters did not delete if character length reach 14 .
try this
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
if ($phone.val().length === 15) {
$phone.val($phone.val() + ' x');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
<form id="example-form" name="my-form">
<label>Phone number:</label><br />
<!-- I used an input type of text here so browsers like Chrome do not display the spin box -->
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX" /><br /><br />
<input type="button" value="Submit" />
</form>
Related
I'm trying to achieve in the input box user can enter only numbers and the date format should be YY/MM/DD.
In the following example I can enter only numbers using replace method.
I want to achieve using the same method when user keyup the numbers format should be YY/MM/DD.
Please drop a comment for more clarification
$(document).on("keyup", "input", function() {
$(this).val($(this).val().replace(/[^0-9\/]/g, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="YY/MM/DD">
Please follow this.
JS
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
$(document).ready(function() {
$("#datePicker").ForceNumericOnly();
$('#datePicker').keyup(function(){
let val = $(this).val()
if(val.length==2)
{
val = val+'/'
$(this).val(val)
}
else if (val.length==5)
{
val = val+'/'
$(this).val(val)
}
})
});
HTML
<input id="datePicker" type="text" maxlength="8">
This question has been asked before back in 2011 Allow only numbers into a input text box but the final code doesn't work in my situation and I did wonder if there was an update scenario.
I am trying to stop all characters other than the numbers 0123456789 from being input.
document.getElementById("text_input").addEventListener("keydown", (eventObject) => {
// Add : after the first 2 chracters
const length = eventObject.target.value.length;
const keyCode = eventObject.keyCode;
if (keyCode != 8 && length === 2) {
eventObject.target.value += ":"
}
// Stop all characters other than 0123456789 from being input
const charCode = (typeof eventObject.which == "number") ? eventObject.which : eventObject.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
});
<input id="text_input" type="text" name="hours">
document.getElementById("extra7").addEventListener("keydown", (eventObject) => {
const length = eventObject.target.value.length;
const keyCode = eventObject.keyCode;
if (
eventObject.key.length === 1 && eventObject.key !== '.' && isNaN(eventObject.key) && !eventObject.ctrlKey ||
eventObject.key === '.' && eventObject.target.value.toString().indexOf('.') > -1
) {
eventObject.preventDefault();
}
});
<input type="text" class="textfield" value="" id="extra7"/>
Credit card expiration date: mm/yy
Whenever I enter two numbers, I need add /, but currently when I delete the third number, he will only delete one number. How can I delete the third number along with the slash?
Please help thank you.
var characterCount
$('#expiry').on('input', function(e) {
if ($(this).val().length == 2 && characterCount < $(this).val().length) {
$(this).val($(this).val() + '/');
}
characterCount = $(this).val().length
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="expiry" type="text" />
with plain js
const inp = document.querySelector('#expiry')
inp.onkeydown = function() {
const key = event.keyCode || event.charCode;
if (key !== 8 && key !== 46 ) {
if (inp.value.length == 2) {
inp.value= (inp.value+'/');
}
}
if (( key == 8 || key == 46 ) && inp.value.length === 4) {
inp.value = inp.value.slice(0,3)
}
};
<input id="expiry" type="text" />
You can add an additional keyup event and when the backspace key is hit, remove any trailing slash from the end of the value.
I'd also recommend to set the maxlength, pattern and inputmode attributes on the input.
var characterCount;
$('#expiry').on('input', function(e) {
if ($(this).val().length == 2 && characterCount < $(this).val().length) {
$(this).val($(this).val() + '/');
}
characterCount = $(this).val().length
}).on('keyup', function(e) {
if (e.which === 8) {
$(this).val($(this).val().replace(/\/$/, ''))
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="expiry" type="text" maxlength="5" pattern="^\d{2}/\d{2}$" inputmode="numeric" />
this maybe a simple question but not for me. I have a form that has a phone number field in i have JS to restrict users to a certain format. The problem is when they input less then 10 digits it still allows them to submit.
Here is my js:
$('#phone-number')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('(' + String.fromCharCode(e.keyCode) + '');
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
This is the phone number box:
<div class="form-group">
#Html.LabelFor(m => m.phoneNumber)
#Html.TextBoxFor(m => m.phoneNumber, new { #class = "form-control", minlength = "5", oncopy = "return false", onpaste = "return false",
id = "phone-number" ,name = "phone-number", type = "text", maxlength = "14" , placeholder = "(XXX) XXX-XXXX"
})
</div>
This is the Submit btn
<button type="submit" class="btn btn-primary" value="Results" id="Submit" disabled="disabled" >Submit</button>
I don't know if you need this information but this Enable the submit btn after the boxes are filled in JS
$("input[type=text]").keyup(function () {
if
(
$("#firstName").val().trim().length !== 0 &&
$("#lastName").val().trim().length !== 0 &&
// $("#phoneNumber").val().trim().length !== 0 &&
$("#address").val().trim().length !== 0
) {
$("#Submit").removeAttr("disabled");
$("#Submit").addClass("btn--primary");
} else {
$("#Submit").attr("disabled", "disabled");
}
});
Thank you and sorry if it is an easy question but I tried in many places.
What you want to do is stop the form submission from going through. You can do this by attaching an on submit event to the form and preventDefault within it. For example:
$('#FORM_ID').submit(function (e) {
if ($('#phone-number').val().replace(/[^\d]/g,'').length < 10){ // check if phone number is less than 10 digits
// phone number is less than 10 digits, prevent form submission
e.preventDefault()
return false
}
})
Let me know if you have any questions!
Here's how my validation of the phone number input ($('#phone-number').val().replace(/[^\d]/g,'').length < 10) works:
I get the value of the phone number input: $('#phone-number').val()
I remove any characters that are not numbers replace(/[^\d]/g,'')
Then I get the length of the resulting numbers. If it's less than 10, I prevent the form from submitting via e.preventDefault()
Note: you will have to replace #FORM_ID with the id of the form you want to run this validation for.
Have you considered using an input with type="tel" and the pattern attribute? It doesn't disable the submit button like you asked, but it can validate the user input against a certain pattern.
Below a few examples of inputs using a pattern. The first accepts exactly 10 digits, the second accepts 10 digits or more, the third accepts a strict format similar to your inputs placeholder:
<form>
<input type="tel" pattern="[0-9]{10}" placeholder="Exactly 10 digits"><br>
<input type="tel" pattern="[0-9]{10,}" placeholder="10 digits or more"><br>
<input type="tel" pattern="\([0-9]{3}\) [0-9]{3}-[0-9]{4}" maxlength="14" placeholder="(123) 456-7890"><br>
<input type="submit">
</form>
thank you for the help but for me this works the best and easiest.
//This script will prevent the user from Submitting if the Phone number box is less than
function validatePhone() {
var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
var phoneNumber = $("#phone-number").val();
if (phoneNumberPattern.test(phoneNumber)) {
return true;
}
return false;
}
//Here we make sure that all boxes are filled then Submit.
$("input[type=text]").keyup(function () {
if
(
validatePhone()
) {
$("#Submit").removeAttr("disabled");
$("#Submit").addClass("btn--primary");
} else {
$("#Submit").attr("disabled", "disabled");
}
});
//this is the submit btn
<div class="form-group">
<button type="submit" class="btn btn-primary" value="Results" id="Submit" disabled="disabled">Submit</button>
</div>
I wanted a text field to take only numbers ans some control keys and number should be exactly four digit long, not less not more. My validation code is
function checkValidInput()
{
$(".validateYearTextBox").keydown(function(event)
{
// Allow only delete, backspace,left arrow,right arraow and Tab
if (
event.keyCode == 46 //delete
|| event.keyCode == 8 //backspace
|| event.keyCode == 37 //leftarow
|| event.keyCode == 39 //rightarrow
|| event.keyCode == 9 //tab
)
{
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode <96 ||event.keyCode > 105) ) {
event.preventDefault();
}
}
});
$(".validateYearTextBox").keyup(function(event)
{
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, valore.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
}
Here, my first validation is working, but my send one is not working.
I am calling this validation function in my aspx page like this
<script type="text/javascript">
$(document).ready(function(){
checkValidInput();
}
</script>
What is going wrong?
Simplify it:
function checkValidInput() {
// Allow only delete, backspace, left arrow, right arrow,
// Tab, ctrl+v and numbers
$(".validateYearTextBox").keydown(function(event) {
if (!((event.keyCode == 46 ||
event.keyCode == 8 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 9) ||
(event.ctrlKey && event.keyCode == 86) || // Edit: Added to allow ctrl+v
$(this).val().length < 4 &&
((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105)))) {
// Stop the event
event.preventDefault();
return false;
}
});
// Edit: Added validate after copy+paste.
// This removes non-numeric characters and truncates the length
// to 4 if the user copy + pasted.
$(".validateYearTextBox").change(function(event) {
var value = $(this).val();
value = value.replace(/[^0-9]/g,'');
value = value.substr(0,4);
$(this).val(value);
});
}
$(document).ready(function() {
checkValidInput();
});
http://jsfiddle.net/nwellcome/687kD/
Edit: Personally I like the Masked Input jQuery plugin but that might be a heavy-handed solution if this is all you need to do.
There are many, many jQuery plugins that already do this in one form or another.
One that does mostly1 what you want is Masked Input Plugin. If you can, I recommend using something existing, working and proven, rather than reinventing.
1 The only part that it doesn't seem to do is display an error if a user tries to enter more than n characters but I'm sure you could modify the plugin or add a length check to the <input>
Use regular expression :
enter code here
function validator(elem,msg)
{
var exp=/^([0-9]+)$/; //it only allows for numbers
if(elem.value.match(exp))
{return true;}
else
{
alert(msg);
elem.focus();
return false;
}
}
the html code :
enter code here
<html><head>
<script src="javasript.js" type="text/javascript">
</head>
<body>
<form method=POST>
<input type='text' maxlength=4 name='num' id='num'>
<input type='submit' value=OK onClick="validator(document.getElementById('num'),'Only four numbers and numbers only!');">
</form> //the maxlength in input text tag restrict the maximum length of the input
</body></html>
Here's a simple way of doing it. Stores the old text before an event changes the text. Then check to see if the new text is valid or not. If it isn't, then revert back to the old text. To further ensure the maximum of 4 characters, add a maxlength attribute to all <input type="text"> elements.
jQuery.fn.forceNumericOnly = function() {
return this.each(function() {
var oldText;
$(this).keyup(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(oldText);
else
oldText = $(this).val();
})
$(this).blur(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(newText = oldText);
else
oldText = $(this).val();
});
})
};
$(".validateYearTextBox").forceNumericOnly();
if (document.ExamEntry.examnum.value=="") {
msg+="You must enter your examination number \n";
document.ExamEntry.examnum.focus();
document.getElementById('examnum').style.color="red";
result = false;
}
$('.numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
}).on('paste',function(e){ e.preventDefault();});
Here add class=numeric to input text box'. it will allow only 4 digits if you want to limit size to 2 digits change to e.delegateTarget.value.length>1 and so on as index starts from zero
Use HTML input maxlength attribute for this and also set the size value of fixing width 4 in same input size attribute.
<input type="text" maxlength="4" size="4">
Here is a simple answer that takes care of copy paste and all.
$(document).on("input", ".validateYearTextBox", function() {
var value = this.value
value = value.replace(/\D/g,'');
for (i = 0; i < value.length; i++) {
if (i > 3) {
value = value.replace(value[i], '')
}
}
});