0

I am trying to format number through jQuery in USA phone number format. that is (111) 111 1111 but it doesn't let me delete also it is adding 11th digit and not deleting it. Can anyone help?

$("#no").keypress(function(e) { var value = $(this).val(); if(value.length <= 10) { var first = "(" + value[0]+value[1]+value[2] + ")" + " " + value[3]+value[4]+value[5]+ " " + value[6]+value[7]+value[8]+value[9]; $(this).val(first); $("#no_span").html(first); e.preventDefault(); } if(value.length > 10) { $(this).val($("#no_span").html()); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="no" maxlimit="14"/> <span id="no_span"></span>

1 Answer 1

2

Try this, I used switch statement to add special characters and spaces to the number. There is if statement which shows formated number when it is 10 characters or more. Hope it is what you were looking for, if you would need some different functionality let me know.

$("#no").on('keyup', function() { var value = $(this).val().split('') var output = '' for (var i = 0; i < value.length; i++) { switch (i) { case 0: { output += '(' + value[i]; break; } case 2: { output += value[i] + ') '; break; } case 5: { output += value[i] + ' '; break; } default: output += value[i] } } if (value.length >= 10) $('#no_span').html(output) else $('#no_span').html('') });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="no" maxlimit="14"/> <span id="no_span"></span>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.