javascripthtmljquery-mask

How can i make a text input to start the number 9?


I need a textbox to start with the number 9, how do i do it? The textbox only accepts numbers but i need it to start with the number 9. I've tried it like this but it doesn't work.

$(document).ready(function () { 
            var $phone = $("#phone");
            $phone.mask('900000000', {reverse: false});
        });

Solution

  • $(function(){
       //get the input element to const
       const $phn = $('#phone');
       //add keydown event
       //if value is a length of 1 and code is backspace or delete return false
       //if length is longer than 1 and delete key is pressed, reset to just 9
       $phn.on('keydown', function(e){
           const code = e.which || e.keyCode;
           //keycode 8 = backspace, keycode 46 = delete
           if($phn.val().length === 1 && (code === 8 || code === 46)){
              return false;
           }
           else if(code === 46){
              $phn.val('9');
              placeCursor($phn);
           }
       });
       
       //initialize value to 9 and place cursor
       $phn.val('9');
       placeCursor($phn);
       
       //function to focus and place cursor in input box
       function placeCursor(input){
          $(input)[0].focus();
          $(input)[0].setSelectionRange($(input).val().length, $(input).val().length);
       }
    });
    <input type="text" id="phone" />
    <script
      src="https://code.jquery.com/jquery-3.6.0.slim.min.js"
      integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI="
      crossorigin="anonymous"></script>