Search code examples
jqueryjquery-pluginsmaskedtextboxmaskedinput

masked input phone number clears textbox when i submit the page


i have two issues with that:

1) i have phone format something like this:

$('#phone').mask('(999) 999-9999');

so when i submit the form i want to validate if the user has entered all 10 numbers so i tried something like this but

but somehow i am getting the mask character, how can i have just phoe number?

if ($('#phone').length == 10) {
    alert("10");
}
else {
   alert("not 10");
}

2) when i submit the form it clears the phone textbox, how can i keep the phone number in the textbox?

<div>
        Phone Number:
        <input id="phone" type="text" />
        (999) 999-9999
        <br />
        <div id='display'>
            error...</div>
        <input id="submitSignup" type="submit" value="Signup" /><br />
        <br />
                 </div>


$("#submitSignup").click(function (event) {

 if ($('#phone').length == 10) {
        //do something..
   }
  else {
      alert("not 10");
    }
   return; 
});

Solution

  • 1) i have phone format something like this:

    You will want $("#phone").val().length == 10 if you call $('#phone').length you are getting the number of elements matched by the jQuery selector not the value of the text box.

    $('#phone').mask('(999) 999-9999');
    $("#submitSignup").click(function(event) {
        if ($('#phone').val().length == 14) {
            alert("valid");
        }
        else {
            alert("not valid");
            return false; //stop the form to submit, also could use event.preventDefault();
        }
    });
    

    Example on jsfiddle.