I have one textbox for phone number. My phone number should be XXX-XXX-XXX like this format.
I got the solution for XXX-XXX-XXX format, but i don't know how to modify that code.
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
while (val.length > 3) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
newVal += val;
this.value = newVal;
});
http://jsfiddle.net/ssthil/nY2QT/
Since you're using jQuery you can try jquery masked-input-plugin.
There's a jsFiddle for you here where you can see how it works.
The source code for the project on GitHub can be found here.
The implementation is more than simple:
HTML:
<input id="ssn"/>
javascript:
$("#ssn").mask("999-999-999");
UPDATE:
Another good one can be found here.
As far as I can work out, all you really need to do is this:
$('#ssn').keyup(function()
{
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
});
but this will only work when people enter digits, so I'd suggest an introducing an extra check:
$('#ssn').keyup(function(e) {
if ((e.keyCode > 47 && e.keyCode < 58) || (e.keyCode < 106 && e.keyCode > 95)) {
this.value = this.value.replace(/(\d{3})\-?/g, '$1-');
return true;
}
//remove all chars, except dash and digits
this.value = this.value.replace(/[^\-0-9]/g, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="ssn">
A little more on the regex /(\d{3})\-?/g: This replaces group of 3 digits with itself, followed by a dash. The brackets create a back reference to the matched digits, that is used in the replacement string ($1- -> $1 being the back reference).Note that an optional dash is replaced, too, but not included in the back reference. if the input is 123, and the replace pattern would be something like /(\d{3})/g, or /(\d{3}\-?)/g the value would become 123-4, 123--45, 123---456 and so on, doubling the dashes each time.
Warning:
This will give the user some grief, since the arrow keys and such won't work.Luckily, that's an easy fix: Just add the following code at the top of your function:
if (e.keyCode > 36 && e.keyCode < 41)
{
return true;
}
And the arrows work just fine. for other keys (such as delete, backspace, shift etc...) check this page.
For a full example: here's the fiddle
For the formatting XXX-XXX-XXXX here is a simple solution:
if(this.value.trim().length <= 8){
this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
}
Here is an example and you not need any framework or library or npm:
this.phone.addEventListener('keyup', event => {
if(this.phone.value.trim().length <= 8){
this.phone.value = this.phone.value.replace(/(\d{3})\-?/g,'$1-');
}
}
You could also do this if you like:
this.phone.addEventListener('keyup', event => {
if(this.phone.value.trim().length <= 8){
this.phone.value = this.phone.value.replace(/(\d{3})\-?/g,'$1-');
}else{
this.phone.value = this.phone.value.replace(/(\d{4})\-?/g,'$1');
}
}
Replace this this.phone with your value.
I hope this helps.
I found this question while googling for a way to auto-format phone numbers in Javascript. The accepted answer was not ideal for my needs and a lot has happened in the 6 years since it was originally posted. I eventually found the solution and am documenting it here for posterity.
Problem
I would like my phone number html input field to auto-format (mask) the value as the user types.
Solution
Check out Cleave.js. It is a very powerful/flexible and easy way to solve this problem, and many other data masking issues.
Formatting a phone number is as easy as:
var cleave = new Cleave('.input-element', {
phone: true,
phoneRegionCode: 'US'
});
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
for(i=0;i<2;i++){
if (val.length > 3) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
}
newVal += val;
this.value = newVal;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ssn" maxlength="10"/>
You can set input mask on any field in 3 simple steps:
1: First of all call these libraries
http://code.jquery.com/jquery-1.7.2.min.js"
"https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"
2: Create simple form like this :
<form> <input type="text" name="phone" id="phone" /> </form>
3: Then the script code past into your script tag..
$(document).ready(function($) {
$('#phone').mask("99999-9999999-9",{placeholder:""});
});
Related
I have an input field in which the user should only be able to enter digits [0-9].
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = this.value.replace(/[^\d]/g, '');
}
<input type="number" id="integer" />
jsFiddle Demo
The problem is this: When I enter a number (eg. 1234) and then press dot (.), + or - the content of the input field is automatically deleted by the browser (value is set to "" = empty string). But why? Changing the type from number to text seems to fix the problem. But then I lose the up/down arrow functionality of the input field. Any ideas?
HTML 4 has an event called onkeypress. With that attribute we can do this without using additional JS:
<input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">
Here digits from 0 to 9 are allowed using the event.charCode from 48 to 57.
I think the reason that the browser clean the input value it is because a string with two dots it is not a number.
Some corrections about your code:
You need to change your expression regular if you want to accept number with decimal part. Now, you are only express that you want to accept digits [0-9] and no more chars.
To accomplish want you want, you need to change /[^\d]/g to /[^\d.]/g.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger()
{
this.value = this.value.replace(/[^\d.]/g, '');
}
<input type="number" id="integer" />
HOWEVER: If you define your input as number type, the regular expression is not needed. So, you just need to define the input like this and should your to your case:
<input type="number" id="integer" />
[THE SOLUTION]
To fully meet your needs, I came with a solution that catch the keydown event of the input and check if there is any '.' on the input. If yes, I prevent the char to go to the input.
document.getElementById("integer").addEventListener('keydown', restrictToInteger);
var lastCodeWasDot = false;
function restrictToInteger(e)
{
var inputValue = document.getElementById("integer").value;
var isDot = false;
var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.charCode == 190);
console.log(e.keyCode);
if(isDot && (inputValue.indexOf(".") > -1 || inputValue == "" || lastCodeWasDot)) {
e.preventDefault();
}
lastCodeWasDot = isDot;
}
<input type="number" id="integer" />
Explaning the solution:
The line of code var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.keyCode == 190) || false; is needed because cross browser compatibility.
I don't now why but if you try to get the value from an input number type in the firefox, and if the value finishes with a dot, the value that you will get will be without the last dot of the input. To fix that, I needed to add the variable lastCodeWasDot to fix this issue.
NOTE: The number input can accept floating point numbers, including negative symbols and the e or E character (check out this post)
Based on the answers of Alexandru-Ionut Mihai and natchiketa I created the following solution:
document.getElementById("integer").addEventListener("input", allowOnlyDigits);
function allowOnlyDigits() {
if (this.validity.valid) {
this.setAttribute('current-value', this.value.replace(/[^\d]/g, ""));
}
this.value = this.getAttribute('current-value');
}
<input type="number" id="integer" />
On input the value is checked for validity. If it is valid, all non-digits are removed and the value is stored in a custom attribute of the element. If the value is not valid, the previous value is restored.
Notes:
The RegEx-replace is required only for Internet Explorer as it allows you to enter , or . at the end of a number.
Tested in IE, Edge, Chrome and Firefox
Chrome still allows you to enter a + before and one , after the number.
I found one issue: If you initialize the field with a value, the value is lost when you first hit an invalid char on the keyboard.
Another issue: You can't enter a negative number.
The only problem was your input type. Change it to text and it should work !
function validate(e) {
var charCode = e.keyCode? e.keyCode : e.charCode
if (!(charCode >= 48 && charCode <= 57)) {
if(!(charCode>=37 && charCode<=40))
if(charCode!=8 && charCode!=46)
return false;
}
}
<input type="number" id="integer" pattern="[0-9]"
onkeydown="return validate(event)"/>
You can achieve your requirement by copying the old value of input and using setAttribute and getAttribute methods in order to store the values.
function myFunction(input){
input.setAttribute('current-value',"");
input.oninput=function(){
let currentValue=input.getAttribute('current-value');
if(input.value!='' || (currentValue>=1 && currentValue<=9))
input.setAttribute('current-value',input.value);
input.value=input.getAttribute('current-value');
}
}
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
When you call oninput, the <input> element first calls its internal methods to handle the value. This prevents your function from seeing any actual erroneous characters, namely e+-. - all used by JavaScript to format numbers.
You can see this by adding console.log calls before and after changing this.value.
console.log(this.value);
this.value=this.value.replace(/[^\d]/g, '');
console.log(this.value);
There is never any difference!
If you try, for example:
console.log(this.value);
this.value+=1; // or *=2 for numerical fun
console.log(this.value);
you can see a difference.
So your function is hastening the normal internal calls <input type='number'/> would normally make when handling illegal input.
Can't quite see why the field is left blank and not 1 though.
I would switch to a cancelable event like keydown.
That way you can prevent the character from being typed in the first place:
var cancelEvent = function (e) {
e.preventDefault();
return false;
},
restrictToInteger = function restrictToInteger(e) {
var acceptableInput = /[0-9]/g,
clipboardKeys = /[zxcv]/ig,
field = e.key || e.char,
isClipboardOperation = (clipboardKeys.test(field) && e.ctrlKey),
inputIsAcceptable = field ? (
acceptableInput.test(field)
|| field.length > 1
|| isClipboardOperation
) : true;
if (!inputIsAcceptable) {
cancelEvent(e);
}
},
ensureIntegerValueOnPaste = function ensureIntegerValueOnPaste(e) {
var data = e.clipboardData || e.dataTransfer,
text = data.getData('text'),
int = parseInt(this.value + text, 10);
if (isNaN(int)) {
cancelEvent(e);
} else {
window.setTimeout(function () {
e.target.value = int;
}, 0);
}
},
input = document.getElementById("integer");
input.addEventListener('keydown', restrictToInteger);
input.addEventListener('drop', ensureIntegerValueOnPaste);
input.addEventListener('paste', ensureIntegerValueOnPaste);
<input type="number" id="integer" />
Updated fiddle: https://jsfiddle.net/838pa8hv/2/
Disclaimers:
Only tested in Chrome.
The test for field.length > 1 is to catch non-numeric keys that are valid as the up/down arrows have a value of ArrowUp and ArrowDown respectively. This also allows for keys like Shift (or Home, Backspace, Delete, etc.) to be pressed as well.
Edit:
To handle pastes (and drops), you can do the same thing in those respective events. Updated fiddle and code snippet above.
Edit:
If the expected usability is to be able to paste/drop partial numbers into the field and to not allow negative integers, then you can just change how int is defined in the ensureIntegerValueOnPaste function. Updated fiddle and code snippet above.
You don't need regular expression, you can use parseFloat() function. Your input type remains unchanged, there are still "arrows" to increase/decrease number and also it makes sure that your input will not start with zero.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = parseFloat(this.value);
}
<input type="number" id="integer" />
You have to check if the value is not a number and then stop user.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger(e)
{
if(isNaN(e.data)){
alert("only numbers allowed");
}
}
<input type="number" id="integer" />
For a project i need a initial textfield which use the every first letter of a forname and bornnames. So basically the field needs to autoformat the input by user. If i fill in my initials MGJ it needs to be M.G.J. (after every letter he must put in the point).
Be aware;
The webform made with Webform module Drupal, so i only could use css or Javascript.
Are there some easy option for that?
Regards,
Martijn
http://nosir.github.io/cleave.js/ you can use this library to format your input the easy way.
Or you can do it like this in JS
var input = document.querySelector('#initials');
input.addEventListener('focusout', function() {
this.value = this.value.split('').join('.');
})
<input type="text" id="initials" />
all you need to do is to split your string and then join with a dot.
string.split('').join('.');
Oke I allready found the solution my own; i used:
`$( document ).ready(function() {
if ($(".input")[0]){
$(".input").focusout(function() {
var initials = this.value.replace(/\./g,'');
this.value = initials.split('').join('.');
});
}
});
})( jQuery );`
Late answer; I needed the same thing but wasn't happy with the current answers.
document.getElementById('initialsOnly').addEventListener('keyup', function(e) {
if (e.code === 'Backspace') {
this.value = this.value.slice(0, -1);
} else {
const newString = this.value.replace(/[\W\d]/g, '').split('').join('.').toUpperCase();
this.value = newString + (newString.length > 0 ? '.' : '');
}
});
<input id="initialsOnly" type="text" />
I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Auto-format structured data (phone, date) using jQuery plugin (or failing that vanilla JavaScript)
Insert space after certain character into javascript string
I am trying to write a script that handles product keys like the ones you see on the back of software and games.
I would like so when the user is inputing their key code the '-' are inserted every 5 characters for 5 sets of characters. Ex(ABCDE-FGHIJ-KLMNO-PQRST-UVWXY). So when the user enters ABCDE as soon as the 'E' is enetered a '-' is inserted immeditly after via jQuery or JavaScript.
Thanks In Advance.
Comment if you have any questions or if I was unclear :)
Form:
<form method="post" action="process.php">
<p>Key: <input name="key" id="key" size="40"></p>
<p><input type="submit"></p>
</form>
You can use http://digitalbush.com/projects/masked-input-plugin/
jQuery(function($){
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa");
});
HTML:
<fieldset id="productkey">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
<input type="text" size="5" maxlength="5">
</fieldset>
JavaScript:
$( '#productkey' ).on( 'keyup', 'input', function () {
if ( this.value.length === 5 ) {
$( this ).next().focus();
}
});
Live demo: http://jsfiddle.net/XXLND/3/show/
You can also enhance the code, so that when the last text-box is filled out, a processing mechanism is activated:
$( '#productkey' ).on( 'keyup', 'input', function () {
var $field = $( this );
if ( $field.val().length === 5 ) {
if ( $field.is( ':last-of-type' ) ) {
$field.blur();
processKey();
} else {
$field.next().focus();
}
}
});
Live demo: http://jsfiddle.net/XXLND/4/show/
Simply because I don't like JQuery :)
function insertSpace(string, part, maxParts) {
"use strict";
var buffer = string.split("-"), step, i;
for (i = 0; i < buffer.length; i += 1) {
step = buffer[i];
if (step.length > part) {
buffer[i] = step.substr(0, part);
buffer[i + 1] = step.substr(part) + (buffer[i + 1] || "");
} else if (step.length < part) {
if (i == buffer.length - 1) {
if (!step) {
buffer.pop();
}
} else {
buffer[i + 1] = step + (buffer[i + 1] || "");
buffer.splice(i, 1);
i -= 1;
}
}
}
buffer.length = Math.min(maxParts, buffer.length);
return buffer.join("-");
}
How about using http://digitalbush.com/projects/masked-input-plugin
With that plugin, the following:
jQuery(function($){
$("#key").mask("99999-99999-99999-99999-99999",{placeholder:" "});
});
or, if your key is all letters use:
$("#key").mask("aaaaa-aaaaa-aaaaa-aaaaa-aaaaa",{placeholder:" "});
or, if it's alpha/numeric use:
$("#key").mask("*****-*****-*****-*****-*****",{placeholder:" "});
Here's one approach:
// binds to both the 'keyup' and 'paste' events
$('input:text').on('keyup paste', function(e) {
var that = $(this), // caches the $(this)
val = that.val(), // access the value of the current input
key = e.which, // determines which key was pressed
allowed = [8, 46, 9, 16]; // defines 'allowed' keys (for editing/focusing)
// backspace, delete, tab, shift
if ($.inArray(key, allowed) == -1) {
// if the pressed key is *not* an 'allowed' key
if (val.length == 5) {
// focuses the next element
that.next().focus();
}
else if (val.length > 5) {
// truncates the string, if greater than 5 characters
that.val(val.substring(0, 5));
that.next().focus();
}
}
});
JS Fiddle demo.
The advantage of this approach is that rather than masking or manipulating the entered string, and accounting for multiple edge-cases, you're simply aiding the user by moving the focus at the right point. And, in this case, also allowing the user to refocus the re-edit the previously entered data.
two things:
One the user experience side, I would avoid dynamically adding character in the input field as the user type a code. Depending on the environment you run the risk to interfere with what the user type.
However, the '-' helps user typing the code since this is a reference point for him. So I would suggest to have an input field and to show a pretty version of the code next to it (or make the field invisible and manage the focus of the field yourself).
For the php code, instead of adding a character every 5 characters I would do the opposite and simplify the code by removing all the unnecessary characters.
Something like that
if ( str_replace('-', '', $userInputKey)==str_replace('-', '', $officialKey) {
echo 'Yeah! Valid key!';
}
I am wanting to only have input values of 01,02,...,09,10,11,12,..,15 permissible in my text field. Please help the newbie with a sample code on how to achieve this. (not using HTML5 yet)
try:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["YourTextBoxID"].value;
var y = parseInt( x , 10 )
var i=15;
if (y>i)
{
alert("Out of range");
return false;
}
}
</script>
A Sample, why not allow user to enter only numbers? Try this out
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt) ' Allow user to enter only numbers
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (((charCode > 47) && (charCode < 58 ) ) || (charCode == 8))
return true;
return false;
}
function isless() ' do not submit if greater than 15
{
var num = document.getElementById('num_txt').value
var y = parseInt( num , 10 )
if ( y > 15 )
return false;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM onsubmit="isless()" action="some.php">
<INPUT id="num_txt" onkeypress="return isNumberKey(event)" type="text" >
</FORM>
</BODY>
</HTML>
Well, since you tagged your question with "regex", the regex you want is something like this:
/^(0[\d]|1[1-5])$/
Or if you want to make the initial "0" optional:
/^(0?[\d]|1[1-5])$/
As far as how you use that, well, if you show the code you've got so far I can advise how to fit it in...
I think you can use comboBox.. some code to get started :
<select >
<option> 01 </option>
<option> 02 </option>
</select>
http://www.w3schools.com/tags/tag_select.asp
You have a couple of choices. Users who use a keyboard like to enter text manually so for them it is best to put a hint on the screen that the input should have a value from '01' to '15'. Let the user enter whatever they want and validate it when the form is submitted.
Another option is to use a select element with the values you want, or a sequence of radio buttons. It all depends on your users, the data you are collecting (e.g. dates, counts, ages, whatever).
So find out what your users would like, then implement it. Client side validation is all about making life better for the user, it is not a way of forcing them to do what you want—that's what server side validation is for. :-)
Here's a somewhat brittle, but complete solution for this:
In this case, you'd have a text input with an id of test:
<input type="text" id="test"/>
Here's your script:
var numbers = [48,49,50,51,52,53,54,55,56,57];
$("#test").bind("keyup",function(e){
var num = numbers.indexOf(e.which),
t = $(e.target),
v = t.val(),
len = v.length;
if(len > 2){
t.val(v.match(/(.+?).$/)[1]);
} else {
if(v[0] == 1){
if(v[1] && v[1] > 5){
t.val(15);
}
} else if(v[0] != 0) {
t.val("");
}
}
});
basically, I assign the key codes of all letters to corresponding indices of an array.
Then, on each key down, we figure out what key it is, and if it's in position 0, check if it's 0 or 1.
if it's in position 1, check if it's greater than 5 as long as the first number is 1.