0

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>

1
  • 1
    Well, right now you don't have a function. Commented Oct 24, 2018 at 19:09

1 Answer 1

1

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>

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

2 Comments

Thanks! It was just I needed. But, If instead of add the plus sign I want that, the function adds the following value: +44. I try to add in this line $(this).val("+44" + num); but, instead of adding those lines in the textbox, the input is filled by every time I delete a character. Is there something way to restart the method replace to the default value that I have established. (+44)
@M4uriXD Updated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.