How to change Phone number format in input as you type?
In your case
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/js/jasny-bootstrap.min.js"></script>
<input type="text" class="form-control" data-mask="(999) 999-9999">
with jasny bootstrap plugin
$("input[name='phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d+)$/, "($1)$2-$3"));
});
This will work for sure and will properly handle populating the full string at once (e.g., 1234567890).
/* example jquery use */
$("input[name='phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d+)$/, "($1)$2-$3"));
});
/* use your css to beautify the form */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- form input for example user -->
<form>
<input type="text" name="phone" placeholder="Phone Number" />
</form>
You've probably already solved this problem, but it's worth noting for future reference that anyone else with the need to apply multiple masks to a control may want to explore this inputmask plugin.
It has more callbacks, settings and many out of the box mask types(be sure to take a look at the extension files). You can also define multiple masks for a control, and the plugin will try and apply the appropriate mask based on the value.
Here is a fiddle to demo the previous statement:
$(window).load(function()
{
var phones = [{ "mask": "(###) ###-####"}, { "mask": "(###) ###-##############"}];
$('#textbox').inputmask({
mask: phones,
greedy: false,
definitions: { '#': { validator: "[0-9]", cardinality: 1}} });
});
<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='textbox' />
This was very helpful, I only add some code to make it works when user delete some characters, I gave the option of entering only numbers and a max length. This works for me :)
$(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', '14');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="phone-format" type="text" placeholder="Phone Number">