简体   繁体   中英

I have a problem with a function in javascript

I have a problem with my function in javascript, I try to replace automatically the first character when a user types any character, for example.

If the user types the letter a, in the input (with my function) replace that letter with the plus sign (+).

I want to add in my function a condition that allows to add automatically the plus sign at the beginning of the input and if is possible besides mustn't allow to delete the first character from the input.

Now my function allows to write only numbers.

  <div> <label>Write a phone number:</label>&nbsp; <input type="text" maxlength="12" onkeypress="return number(event)"/> </div> <script type="text/javascript"> function number(e){ var tecla = e.keyCode; if (tecla==8 || tecla==9 || tecla==13){ return true; } var patron =/[0-9+]/; var tecla_final = String.fromCharCode(tecla); return patron.test(tecla_final); } </script> 

Updated, if you want past +44
Try to this one, and change if you need it

 function phoneMask() { num = $(this).val().replace(/\\+4{1,2}|\\D/g,''); $(this).val("+44" + num); } $("#test").keyup(phoneMask); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <label>Write a phone number:</label>&nbsp; <input type="text" maxlength="12" id="test"/> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM