0

i need a jquery solution to pre-fill input box with values while user types.. For e.g if the user is adding a phone number like 1234567890 i need it to automatically change the text to (123)456-7890 as the user types,i is there any way we can do this using jquery??

michelem
  • 14,430
  • 5
  • 50
  • 66

1 Answers1

1

Try this,

$('#phone-number', '#example-form')

 .keydown(function (e) {
  var key = e.charCode || e.keyCode || 0;
  $phone = $(this);

  // Auto-format- do not expose the mask as the user begins to type
  if (key !== 8 && key !== 9) {
   if ($phone.val().length === 4) {
    $phone.val($phone.val() + ')');
   }
   if ($phone.val().length === 5) {
    $phone.val($phone.val() + ' ');
   }   
   if ($phone.val().length === 9) {
    $phone.val($phone.val() + '-');
   }
  }

  // Allow numeric (and tab, backspace, delete) keys only
  return (key == 8 || 
    key == 9 ||
    key == 46 ||
    (key >= 48 && key <= 57) ||
    (key >= 96 && key <= 105)); 
 })
 
 .bind('focus click', function () {
  $phone = $(this);
  
  if ($phone.val().length === 0) {
   $phone.val('(');
  }
  else {
   var val = $phone.val();
   $phone.val('').val(val); // Ensure cursor remains at the end
  }
 })
 
 .blur(function () {
  $phone = $(this);
  
  if ($phone.val() === '(') {
   $phone.val('');
  }
 });
Dinith Minura
  • 1,446
  • 2
  • 12
  • 24
  • Thanks, this solution worked for input box, but can we use the same solution for a content-editable true div . I tried changing val to html, but it doesn't seem to work properly – Shivika Sharma Sep 02 '15 at 10:06