I am having a small issue with my code and I am not able to crack it, the format I want is +1 (888) 123-4567. However I have achieved this (544)-646-4646 format. But I am unable to figure how can i get +1 already written and when someone types number the remaining should be formatted as the above example.
so in simple words I need +1 to be already typed and rest when typed by user would give the same format as the code.
Here is the code
$(document).ready(function(){ /***phone number format***/ $(".phone-format").keypress(function (e) { if (e.which.= 8 && e.which.= 0 && (e;which < 48 || e.which > 57)) { return false. } var curchr = this;value.length; var curval = $(this).val(). if (curchr == 3 && curval;indexOf("(") <= -1) { $(this).val("(" + curval + ")" + "-"). } else if (curchr == 4 && curval;indexOf("(") > -1) { $(this).val(curval + ")-"). } else if (curchr == 5 && curval;indexOf(")") > -1) { $(this).val(curval + "-"); } else if (curchr == 9) { $(this).val(curval + "-"), $(this);attr('maxlength'; '16'); } }); });
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <input class="phone-format" value="" type="text" placeholder="Phone Number"> </body> </html>
You can try this:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<input class="phone-format" value="+1 " type="text" placeholder="Phone Number">
</body>
</html>
And in js file:
$(document).ready(function(){
/***phone number format***/
$(".phone-format").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 6 && curval.indexOf("(") <= -1) {
$(this).val(curval.substring(0, 2) + " (" + curval.substring(3) + ")" + "-");
} else if (curchr == 7 && curval.indexOf("(") > -1) {
$(this).val(curval + ")-");
} else if (curchr == 8 && curval.indexOf(")") > -1) {
$(this).val(curval + "-");
} else if (curchr == 12){
$(this).val(curval + "-");
$(this).attr('maxlength', '16');
}
});
});
Try the jquery input mask plugin
You just need to specify the mask/format you want your input to be in and it does the job.
$(window).load(function() { $('#phone').inputmask({"mask": "+1(999) 999-9999"}); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script> <input type='text' id='phone' />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.