Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

jquery - How to change Phone number format in input as you type?

My CodePen: http://codepen.io/leongaban/pen/cyaAL

I have an input field for a phone number which allows up to 20 characters (for international numbers).

I'm also using the Masked input jQuery plugin by Josh Bush to format the phone number in the input to make it 'pretty'.

enter image description here

  • My problem is that in the requirements when the phone is 10 digits or less, it should use the Masked input formatting.

  • However when the phone number is longer then 10 digits, the formatting should be removed.



Here is my current: CodePen, Cell Phone is the input field where I'm trying to accomplish this. Work Phone is an example of the default functionality of the Mask input plugin.

How would you go about this problem?

jQuery for Cell Phone input field:

case '2':
    console.log('created phone input');
    $('.new_option').append(myphone);
    $('.added_mobilephone').mask('(999) 999-9999? 9');
    $('.added_mobilephone').keypress(function(event){

      if (this.value.trim().length > 10) {
        console.log('this.value = '+this.value.trim());
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }

      /*if (this.value.length < 9) {
        console.log(this.value);
        console.log('less then 10');
        $('.added_mobilephone').mask('(999) 999-9999? 9999999999');
      } else if (this.value.length > 9) {
        console.log(this.value);
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }*/
    });
    break;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$("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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...