In general, there is an input field where the phone number is entered

How to make it so that it is checked on the fly, if the first character "0" is entered, then the automatic machine adds "38" to that character "0".

That is, the user enters the phone number 05 and so on, and he immediately knocks out 3805 and so on. Through the mask is not necessary. In this way it is necessary

  • In js there is a function charAt to it and check using keyboard events. - And

2 answers 2

A simple example: https://jsfiddle.net/9h73fek1/2/

 <input type="text"> <script> var input = document.body.children[0]; input.oninput = function() { if(input.value[0] == 0 && input.value != '') { input.value = 38 + input.value; } }; </script> 
  • And in what place is the verification of the first symbol here, I don’t see the point of view? How do you check if I put 05 there right away? - And
  • @And Corrected, did not think about insertion - I apologize. Here is a test if (input.value [0] == 0 && input.value! = '') - Roman Tokarev
  • @And Why do you think so? Any string is an array of characters, and accordingly the first element of this array is the first character. Verified - Roman Tokarev
  • Thanks for the tip, your solution came in handy, and the small, concise code - Vladimir Tytykalo
  • @ Vladimir Tytykalob it can be made even shorter and more concise without any !='' Etc. without function and input[0] - arrays. - And

 $(document).on('keydown', '#example', function(e) { if ($('#example').val().length == 0 && e.key == 0) { $('#example').val('38'); } if ($('#example').val().length == 3 && e.keyCode == 8) { $('#example').val(''); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="example"/>