I'm trying to implement a customised input that can use left or right arrow key to select the digit and use up/down arrow key to increment/decrement the digit. Here's the code in jsfiddle: http://jsfiddle.net/uk5t3z4d/48/. However, I have two problems:
I cannot add digit using the number pad, the input always stays at X.XX
When I use another function I wrote (parseLocalFloat which is commented out), the output stops displaying anything, and I cannot use the left and right key to select the digit etc.
How can I overcome these two issues? Please shed a light on me, thanks!
HTML
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>
JavaScript
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
//var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var before = $(this).val().substring(0,curPos);
var after = $(this).val().substring(curPos+1);
var cur = Number($(this).val().substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $(this).val().length) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
if(!gotCode) {
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
as for the "get number keys to work":
as stated you need to add the keys you want to support:
if(e.keyCode >= 48 && e.keyCode <= 57) {
var num = e.keyCode - 48; // 0=48; 9=59
$(this).val(before + '' + num + '' + after);
gotCode = true;
e.preventDefault(); // otherwise a new number is added as well
}
(this needs to come before the if (!gotCode) ... )
as for the customFloat: the the response from Moishe
For #1:
if(!gotCode) {
e.preventDefault();
return false;
}
ensures that if gotCode is false the default event (which in this case is the default keydown event) will not occur.
gotCode only seems to be true if keyCode is equal to 37, 38, 39, or 40 (the arrow keys). You are essentially preventing the other keys (like number keys) from having any effect on the textBox.
You probably would like to enable the number keys (when shift or caps aren't on) and number pad keys.
Additionally, you may want to check that the cur is a number (and not .) before attempting to increment or decrement its value.
You could do:
var isNumberKey = (
( e.keyCode >= 48 //is more than or equal to 0 key
&& e.keyCode <= 57 //is less than or equal to 9 key
&& !e.shiftKey) //shift key or cap key not on
|| ( e.keyCode >= 96 //more than or equal to 0 key in number pad
&& e.keyCode <= 105)); //less than or equal to 9 key in number pad
if(!gotCode && !isNumberKey) { //not arrow key or number key
console.log(e);
e.preventDefault();
return false;
}
For #2:
var inputBox = parseLocalFloat(document.getElementByID('in').value);
is setting inputBox to whatever parseLocalFloat returns which happens to be a number.
This is problematic because you then attempt to attach a keyUp event to that number instead of the inputBox:
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = inputBox.value;
}
You may want to instead call parseLocalFloat on the number and set the out textBox's value to that:
var inputBox = document.getElementById('in');
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
function createSelection(field, start, end) {
if( field.createTextRange ) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if( field.setSelectionRange ) {
field.setSelectionRange(start, end);
} else if( field.selectionStart ) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
function getLocalDecimalSeparator() {
var n = 1.1;
return n.toLocaleString().substring(1,2);
}
function parseLocalFloat(num) {
return +(num.replace(getLocalDecimalSeparator(), '.'));
}
var inputBox = document.getElementById('in');
// var inputBox = parseLocalFloat(document.getElementByID('in').value);
inputBox.onkeyup = function(){
document.getElementById('out').innerHTML = parseLocalFloat(inputBox.value);
}
$('#in').on("keydown", function(e){
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if(curPos !== endPos) {
createSelection(this, curPos, curPos+1);
}
// get the position
if(e.keyCode == 37){
curPos--;
gotCode=true;
}
if(e.keyCode == 39){
curPos++;
gotCode=true;
}
var $thisVal = $(this).val();
var before = $thisVal.substring(0,curPos);
var after = $thisVal.substring(curPos+1);
var cur = Number($thisVal.substring(curPos, curPos+1));
// avoid adding extra stuff
if(curPos < $thisVal.length && !isNaN(cur)) {
if(e.keyCode == 38) {
cur++;
if(cur > 9) cur = 0;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
if(e.keyCode == 40) {
cur--;
if(cur < 0) cur = 9;
$(this).val(before + '' + cur + '' + after);
gotCode=true;
}
}
var isNumberKey = ((e.keyCode >= 48 && e.keyCode <= 57 && [16, 20].indexOf(e.keyCode) == -1 && !e.shiftKey) || (e.keyCode >= 96 && e.keyCode <= 105));
if(!gotCode && !isNumberKey) {
console.log(e);
e.preventDefault();
return false;
}
var field = this;
window.setTimeout(function(){
createSelection(field, curPos, curPos+1);
}, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display" id="out"></div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>
Related
How can I create an input field for currency? I'm looking for it to work as follows:
Initial: 0.00
Type "1": 0.01
Type "2": 0.12
Type "5": 1.25
I'm pretty new with web design, so I'm looking for a simpler solution. I saw a similar question & answer to this question with an Angular solution, but I'm unsure how to implement that into my HTML project. I have a simple folder with HTML files in it. Thanks!
A little tricky
Working Demo
document.getElementById("demo").onkeydown = function (e) {
//console.log(e.keyCode);
if (e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 8 && e.keyCode != 46)
e.preventDefault();
if (e.keyCode == 8 || e.keyCode == 46) {
//If already key down (backspaceOrDel=1) then no affect
if (backspaceOrDel == 1)
e.preventDefault();
else
backspaceOrDel = 1;
return;
}
if (e.keyCode < 48 || (e.keyCode > 57 && e.keyCode <96) || e.keyCode > 105 )
return;
try {
var val = this.value;
var val1 = 0;
if (val == 0) {
val1 = e.key / 100;
}
else {
//very tricky. We needed val1=val*10+e.key but it does not
//work correctly with floats in javascript.
//Here you have to different than android in logic
var val1 = parseFloat(val) * 1000;
val1 += parseFloat(e.key);
val1 = val1 / 100;
}
val1 = val1.toFixed(2);
if (!isNaN(val1))
this.value = val1;
}
catch (ex) {
alert("Invalid Amount");
}
};
<style>
.amount_tendered {
text-align: right;
font-size: 24px;
width: 200px;
}
</style>
<form>
<input class="amount_tendered" id="text" type="number" min="0" value="0.00" onkeyup="formatNum(this);" onclick="this.select(); activated();">
</form>
<script type="text/javascript">
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
function formatNum(obj){
var str = obj.value;
switch (true){
case str.length==1:
str = '0.0' + str;
break;
case str.length==3:
str = '0' + str;
}
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "." && (str.length - i)!=3) indices.push(i);
}
for(var i=0; i<indices.length;i++) {
str = str.replace('.','');
}
indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === ".") indices.push(i);
}
if (indices.length==0){
str = str.splice(str.length-2, 0, ".");
}
if (str[0]=='0' && str[1]!='.'){
str = str.replace('0','');
}
obj.value = str;
}
</script>
I have text area controls in my page and I had code it such way that when user click on text area or hit 'ENTER' key that time it will create bullet-list in text area. But problem is that if user click on text area and it will create bullet-list but if user does not type anything in text area then it should get empty and bullet should be removed. In simple way text area bullet-list should get removed if it has no data in it.
And one more thing is to prevent user deleting bullet from text area.
here is my code :
<textarea name="MondayAcomp" id="MondayAcomp" cols="45" rows="5" onKeyDown="if(event.keyCode == 13) return false;" onKeyUp="bulletOnEnter(this.id)" onFocus="onfoc(this.id)" onBlur="onFocOff(this.id)" style="margin: 0px; width: 200px; height: 219px;"></textarea>
Javascript functions:
function onfoc(id) {
if (document.getElementById(id).value == "") {
document.getElementById(id).value += '• ';
}
}
function onFocOff(id) {
if (document.getElementById(id).value == '• ') {
document.getElementById(id).empty;
}
}
function bulletOnEnter(id) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
event.preventDefault();
document.getElementById(id).value += '\n• ';
}
var txtval = document.getElementById(id).value;
if (txtval.substr(txtval.length - 1) == '\n') {
document.getElementById(id).value = txtval.substring(0, txtval.length - 1);
}
}
jsfiddle here
It is not .empty, it is .value = "";.
For the keyCode you need to pass event parameter to your callback function too.
You can prevent adding empty lines, by checking the last line in your return key callback too.
Only way I can imageine, to prevent deleting the bullets, is a loop at the end and check each line start.
function onfoc(id) {
if( document.getElementById(id).value == '' ) {
document.getElementById(id).value +='• ';
}
}
function onFocOff(id) {
if( document.getElementById(id).value == '• ' ) {
document.getElementById(id).value = '';
}
}
function bulletOnEnter(event, id) {
event = event || window.event;
// handle 'return' key
var keycode = event.keyCode || event.charCode || event.which;
var txtval = document.getElementById(id).value;
if( keycode == 13 && txtval.substr(txtval.length - 2) != '• ' ) {
event.preventDefault();
document.getElementById(id).value += '\n• ';
}
// remove possible last empty line
txtval = document.getElementById(id).value;
if( txtval.substr(txtval.length - 1) == '\n' ) {
document.getElementById(id).value = txtval.substring(0, txtval.length - 1);
}
// check if each line starts with a bullet
var lines = document.getElementById(id).value.split('\n')
for( var i = 0, l = lines.length; i < l; i++ ) {
if( lines[i].substr(0, 1) !== '•' ) {
lines[i] = '•' + lines[i];
}
}
document.getElementById(id).value = lines.join('\n');
}
<textarea id="MondayAcomp" onKeyDown="if(event.keyCode == 13) return false;" onKeyUp="bulletOnEnter(event, this.id)" onFocus="onfoc(this.id)" onBlur="onFocOff(this.id)"></textarea>
As additional answer, I converted the code to use jQuery instead of plain JS, because you tagged your question with jQuery.
$('#MondayAcomp').on({
focus: function() {
if( $(this).val() == '' ) {
$(this).val($(this).val() + '• ');
}
},
blur: function() {
if( $(this).val() == '• ' ) {
$(this).val('');
}
},
keydown: function(e) {
if( e.keyCode == 13 ) {
e.preventDefault();
}
},
keyup: function(e) {
var element = $(this),
value = element.val();
// handle 'return' key
if( e.keyCode == 13 && value.substr(-2) != '• ' ) {
e.preventDefault();
element.val((value += '\n• '));
}
// remove possible last empty line
if( value.substr(-1) == '\n' ) {
element.val((value = value.substring(0, value.length - 1)));
}
// check if each line starts with a bullet
var lines = element.val().split('\n')
for( var i = 0, l = lines.length; i < l; i++ ) {
if( lines[i].substr(0, 1) !== '•' ) {
lines[i] = '•' + lines[i];
}
}
element.val(lines.join('\n'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="MondayAcomp"></textarea>
I have this id validation field, i just need to know how i can make the validation and the keydown and keyup functions work on cloned inputs. also inserted data is carrying over to the duplicate fields.
js fiddle- http://www.jsfiddle.net/dawidvdh/xRh9v/
Heres the js:
$(document).ready(function() {
idAmount = [0,1,2,3,4,5,6,7,8,9,10,12,13];
var idinc =1;
var id_val;
jQuery(idAmount).each(function() {
var index = "id"+idinc++;
var id_input = "<input class='id' id="+'"'+index+'"'+" "+" maxlength='1' />";
id_val = $(this).attr('value');
jQuery(id_input).appendTo('#id');
});
$("#clone").click(function () {
var clonedObj=$('#id').clone().insertAfter("#id");
clonedObj.find('.id').each(function(){
this.id='id' + idinc++;
});
});
function Validate() {
jQuery('#error p').remove();
var id_val = '';
$('.id').each(function(){ id_val+=($(this).val());});
var idNumber = id_val;
console.log(id_val);
var correct = true;
if (idNumber.length != 13 || !isNumber(idNumber)) {
correct = false;
}
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
console.log(tempDate);
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var currentYear = (new Date).getFullYear();
var age = currentYear - id_year;
var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
correct = false;
};
// if no error found, hide the error message
if (correct) {
jQuery('.id').css("border","1px solid #9A8B7D");
// clear the result div
jQuery('#result').empty();
// and put together a result message
jQuery('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p><p>AGE: ' + age + '</p>');
jQuery('#status').html("correct");
}
// otherwise, show the error
else {
jQuery('.id').css("border","1px solid #FF0000");
jQuery('#status').html("incorrect")
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('input.id').keydown(function(e){
if(e.keyCode == 8){
$(this).val('');
$(this).prev().val('');
$(this).prev().focus();
Validate()
}
});
$('input.id').on('keyup', function(){
if (this.value.match(/\d+/)) {
var $this = $(this);
if ($this.next('input').length) {
$this.next().focus();
} else {
Validate()
}
}
});
$(".id").keydown(function(event) {
// Allow: backspace, delete, tab, escape, and enter
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
});
HTML:
<div id="id">
<span id="label">ID NUMBER:</span>
<span id="status"></span>
</div>
<button id="clone">clone</button>
<div id="result"> </div>
CSS:
#error {
color: red;
border: 1px solid red;
padding: 5px;
display: none;
}
#result {
padding: 20px;
}
.id {
width:16px;
height:16px;
border:1px solid #9A8B7D;
margin:0;
float:left;
text-align:center;
font-family:'itc_avant_garde_gothic_bookOb',Helvetica,sans-serif;
font-size:11pt;
padding:2px;
}
#label {
float:left;
font-family:'itc_avant_garde_gothic_bookOb',Helvetica,sans-serif;
line-height:18px;
font-size:11pt;
margin-right:10px;
}
The only time that I see you call Validate is here :
$('input.id').on('keyup', function(){
//code
});
and here
$('input.id').keydown(function(e){
//code
});
Which means that the issue is the event handler is not delegated to a static element
$(document).on('keyup', 'input.id', function(){
//code
});
$(document).on('keydown', 'input.id', function(){
//code
});
Binding it to the document will ensure that any dynamically created elements will have the same event delegated to them as any static elements of the same selector.
Forgot the last part.
clonedObj.find('.id').each(function(){
this.id='id' + idinc++;
this.value = ''; //simply add this to remove the value
});
Although, because you're using jQuery, you should try to stick to using jQuery.
clonedObj.find('.id').each(function(){
$(this).prop('id', 'id'+ idinc++).val(''); // chain the commands
});
I have a searchable textbox which populates a div with the search results. The div is scrollable. What I am trying to achieve, is to navigate through the result items with page up and down (keycode 38 & 40). But as soon as I try this, the whole div scrolls, and the result item itself does not take on the new selected css class.
Below is some of my code
this.TagNavigation = function (event) {
var div = $("#TagSearchResults");
var anchors = $("#TagSearchResults a");
var selectedAnchor = $("#TagSearchResults a.selected");
var position = anchors.index(selectedAnchor);
if (event.keyCode == "13" && anchors.length > 0) {
FRAMEWORK.AddUpdateInterventionTags(selectedAnchor.attr("id").split("-")[1] + "|" + selectedAnchor.text(), "add");
}
if (event.keyCode == "13" && anchors.length == 0 && $("#txtTagSearch").val() != "Start typing to search Tags") {
FRAMEWORK.AddNewTag($("#txtTagSearch").val());
}
else if (event.keyCode == "38") {
if (position > 0) {
canClose = false;
selectedAnchor.removeClass("selected");
var newSelectedAnchor = $(anchors.get(position - 1));
newSelectedAnchor.addClass("selected");
$("#txtTagSearch").val(newSelectedAnchor.text());
}
}
else if (event.keyCode == "40") {
if (position <= anchors.length) {
canClose = false;
selectedAnchor.removeClass("selected");
var newSelectedAnchor = $(anchors.get(position + 1));
newSelectedAnchor.addClass("selected");
$("#txtTagSearch").val(newSelectedAnchor.text());
//newSelectedAnchor.focus();
}
}
};
this.AjaxSearch = function (text) {
var div = $("#TagSearchResults");
var anchors = $("#TagSearchResults a");
var selectedAnchor = $("#TagSearchResults a.selected");
var position = anchors.index(selectedAnchor);
if (event.keyCode == "13") {
FRAMEWORK.TagNavigation(event);
}
else if (event.keyCode == "38") {
FRAMEWORK.TagNavigation(event);
}
else if (event.keyCode == "40") {
FRAMEWORK.TagNavigation(event);
}
else if (text.length >= 3) {
FRAMEWORK.RenderSearchResults(text);
}
else {
$("#TagSearchResults").html("");
$("#TagSearchResults").hide();
}
};
As you can see in the TagNavigation function (keycode 40), I tried to set the focus on the active element, but still no success.
Any help please.
You need to check weather the newly selected element has a higher Y value that the bottom of the containing div. If so, then scroll the div by the height of the new element. Change your 'if (event.keyCode == "40")' statement to the following:
this.TagNavigation = function (event) {
var div = $("#TagSearchResults");
var anchors = $("#TagSearchResults a");
var selectedAnchor = $("#TagSearchResults a.selected");
var position = anchors.index(selectedAnchor);
if (event.keyCode == "13" && anchors.length > 0) {
FRAMEWORK.AddUpdateInterventionTags(selectedAnchor.attr("id").split("-")[1] + "|" + selectedAnchor.text(), "add");
}
if (event.keyCode == "13" && anchors.length == 0 && $("#txtTagSearch").val() != "Start typing to search Tags") {
FRAMEWORK.AddNewTag($("#txtTagSearch").val());
}
else if (event.keyCode == "38") {
if (position > 0) {
canClose = false;
selectedAnchor.removeClass("selected");
var newSelectedAnchor = $(anchors.get(position - 1));
newSelectedAnchor.addClass("selected");
$("#txtTagSearch").val(newSelectedAnchor.text());
var newSelectedAnchorPosistion = newSelectedAnchor.offset();
var divPosition = div.offset();
divPosition = divPosition.top;
if (newSelectedAnchorPosistion.top + 1 > divPosition) {
var newPos = div.scrollTop() - newSelectedAnchor.outerHeight();
div.scrollTop(newPos);
}
}
}
else if (event.keyCode == "40") {
if (position < anchors.length - 1) {
canClose = false;
selectedAnchor.removeClass("selected");
var newSelectedAnchor = $(anchors.get(position + 1));
newSelectedAnchor.addClass("selected");
$("#txtTagSearch").val(newSelectedAnchor.text());
var newSelectedAnchorPosistion = newSelectedAnchor.offset();
var divPosition = div.offset();
divPosition = divPosition.top + div.outerHeight();
if (newSelectedAnchorPosistion.top + 1 >= divPosition) {
var newPos = div.scrollTop() + newSelectedAnchor.outerHeight();
div.scrollTop(newPos);
}
}
}
};
I have a problem masking a phone input with jQuery and Masked Input Plugin.
There are 2 possible formats:
(XX)XXXX-XXXX
(XX)XXXXX-XXXX
Is there any way to mask it accepting both cases?
EDIT:
I tried:
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf1").mask("(99) 9999?-9999");
But it doesn't works as I would like.
The closest one was (xx)xxxx-xxxxx.
I would like to get (xx)xxxx-xxxx when I type the 10th number, and (xx)xxxxx-xxxx when I type the 11th. Is it posible?
Try this - http://jsfiddle.net/dKRGE/3/
$("#phone").mask("(99) 9999?9-9999");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 );
$(this).val( first + '-' + lastfour );
}
});
Here is a jQuery phone number mask. No plugin required.
Format can be adjusted to your needs.
Updated JSFiddle.
HTML
<form id="example-form" name="my-form">
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>
JavaScript
$('#phone-number', '#example-form')
.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('('+$phone.val());
}
// 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('');
}
});
Actually the correct answer is on http://jsfiddle.net/HDakN/
Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete
$("#phone").mask("(99) 9999-9999?9");
$("#phone").on("blur", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 5 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );
var lastfour = last.substr(1,4);
var first = $(this).val().substr( 0, 9 );
$(this).val( first + move + '-' + lastfour );
}
});
You need a jQuery plugin for the mask works as well.
-- HTML --
<input type="text" id="phone" placeholder="(99) 9999-9999">
<input type="text" id="telf1" placeholder="(99) 9999*-9999">
<input type="text" id="telf2" placeholder="(99) 9999?-9999">
-- JAVASCRIPT --
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<script>
$(document).ready(function($){
$("#phone").mask("(99) 9999-9999");
$("#telf1").mask("(99) 9999*-9999");
$("#telf2").mask("(99) 9999?-9999");
});
</script>
You can use the phone alias with Inputmask v3
$('#phone').inputmask({ alias: "phone", "clearIncomplete": true });
$(function() {
$('input[type="tel"]').inputmask({ alias: "phone", "clearIncomplete": true });
});
<label for="phone">Phone</label>
<input name="phone" type="tel">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.numeric.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.date.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/inputmask.phone.extensions.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/jquery.inputmask.js"></script>
<script src="https://cdn.jsdelivr.net/gh/RobinHerbots/Inputmask#3.3.7/dist/inputmask/phone-codes/phone.js"></script>
https://github.com/RobinHerbots/Inputmask#aliases
Using jQuery Mask Plugin there is two possible ways to implement it:
1- Following Anatel's recomendations:
https://gist.github.com/3724610/5003f97804ea1e62a3182e21c3b0d3ae3b657dd9
2- Or without following Anatel's recomendations:
https://gist.github.com/igorescobar/5327820
All examples above was coded using jQuery Mask Plugin and it can be downloaded at:
http://igorescobar.github.io/jQuery-Mask-Plugin/
var $phone = $("#input_id");
var maskOptions = {onKeyPress: function(phone) {
var masks = ['(00) 0000-0000', '(00) 00000-0000'];
mask = phone.match(/^\([0-9]{2}\) 9/g)
? masks[1]
: masks[0];
$phone.mask(mask, this);
}};
$phone.mask('(00) 0000-0000', maskOptions);
With jquery.mask.js
http://jsfiddle.net/brynner/f9kd0aes/
HTML
<input type="text" class="phone" maxlength="15" value="85999998888">
<input type="text" class="phone" maxlength="15" value="8533334444">
JS
// Function
function phoneMask(e){
var s=e.val();
var s=s.replace(/[_\W]+/g,'');
var n=s.length;
if(n<11){var m='(00) 0000-00000';}else{var m='(00) 00000-00000';}
$(e).mask(m);
}
// Type
$('body').on('keyup','.phone',function(){
phoneMask($(this));
});
// On load
$('.phone').keyup();
Only jQuery
http://jsfiddle.net/brynner/6vbrqe6z/
HTML
<p class="phone">85999998888</p>
<p class="phone">8599998888</p>
jQuery
$('.phone').text(function(i, text) {
var n = (text.length)-6;
if(n==4){var p=n;}else{var p=5;}
var regex = new RegExp('(\\d{2})(\\d{'+p+'})(\\d{4})');
var text = text.replace(regex, "($1) $2-$3");
return text;
});
The best way to do this is using the change event like this:
$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {
var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );
if( last.length == 3 ) {
var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
var lastfour = move + last;
var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999
$(this).val( first + '-' + lastfour );
}
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.
The best way to do it on blur is:
function formatPhone(obj) {
if (obj.value != "")
{
var numbers = obj.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:' - '};
obj.value = '';
upto = numbers.length;
if(numbers.length < 10)
{
upto = numbers.length;
}
else
{
upto = 10;
}
for (var i = 0; i < upto; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
}
As alternative
function FormatPhone(tt,e){
//console.log(e.which);
var t = $(tt);
var v1 = t.val();
var k = e.which;
if(k!=8 && v1.length===18){
e.preventDefault();
}
var q = String.fromCharCode((96 <= k && k <= 105)? k-48 : k);
if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=8 && e.keyCode!=39) {
e.preventDefault();
}
else{
setTimeout(function(){
var v = t.val();
var l = v.length;
//console.log(l);
if(k!=8){
if(l<4){
t.val('+7 ');
}
else if(l===4){
if(isNaN(q)){
t.val('+7 (');
}
else{
t.val('+7 ('+q);
}
}
else if(l===7){
t.val(v+')');
}
else if(l===9){
t.val(v1+' '+q);
}
else if(l===13||l===16){
t.val(v1+'-'+q);
}
else if(l>18){
v=v.substr(0,18);
t.val(v);
}
}
else{
if(l<4){
t.val('+7 ');
}
}
},100);
}
}
I was developed simple and easy masks on input field to US phone format jquery-input-mask-phone-number
Simple Add jquery-input-mask-phone-number plugin in to your HTML file and call usPhoneFormat method.
$(document).ready(function () {
$('#yourphone').usPhoneFormat({
format: '(xxx) xxx-xxxx',
});
});
Working JSFiddle Link https://jsfiddle.net/1kbat1nb/
NPM Reference URL https://www.npmjs.com/package/jquery-input-mask-phone-number
GitHub Reference URL https://github.com/rajaramtt/jquery-input-mask-phone-number
If you don't want to show your mask as placeholder you should use jQuery Mask Plugin.
The cleanest way:
var options = {
onKeyPress: function(phone, e, field, options) {
var masks = ['(00) 0000-00000', '(00) 00000-0000'];
var mask = (phone.length>14) ? masks[1] : masks[0];
$('.phone-input').mask(mask, options);
}
};
$('.phone-input').mask('(00) 0000-00000', options);
Yes use this
$("#phone").inputmask({"mask": "(99) 9999 - 9999"});
Link here
$('.phone').focus(function(e) {
// add mask
$('.phone')
.mask("(99) 99999999?9")
.focusin(function(event)
{
$(this).unmask();
$(this).mask("(99) 99999999?9");
})
.focusout(function(event)
{
var phone, element;
element = $(this);
phone = element.val().replace(/\D/g, '');
element.unmask();
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}
);
});