How to disable/remove only first space on input field?

前端 未结 4 1270
萌比男神i
萌比男神i 2021-02-11 03:15

Good morning everybody!

I have a case, when I should prevent users to entering space as a first character on input field.

I have a demo here: http://jsbin.com/fo

相关标签:
4条回答
  • 2021-02-11 03:37

    This jQuery function selects all the text inputs when a key is unpressed, removes all whitespace from the beginning of the string and replaces the value of the input:

     <script>
       $(":text").keyup(function () {
         $(this).val($(this).val().replace(/^\s+/,""));
       }
     </script>
    

    I do not recommend to use trim() when blank spaces are replaced directly with keyup() because when you type a space after a word, it will be deleted before you start writing the next word.

    0 讨论(0)
  • 2021-02-11 03:47

    document.querySelector('#test').addEventListener('input',function(e){ if(e.target.value===" ") e.target.value="" })

    this code dosent let users space at the first even if any users select whole text in input (ctrl+a) and then hit the space bar

    0 讨论(0)
  • 2021-02-11 03:50

    Try something like

    $('input').keyup(function () {
      if($(this).val() == '') {
        if(event.keyCode == 32) {
          return false;
        }
      }
    }
    

    This would check for current value, and then it would run the function. Keyup is used, to check for the value after the key has been unpressed. If you use keydown, it would still have the value. Key up would get the value after the key press event has passed.

    Or as others has told you to always keep trimming the value. You can use jQuery trim() method to trim the value, regardless of whether user inputs space character or not.

    $('input').keyup(function () {
      $(this).val($.trim($(this).val()));
    }
    

    This would add the trimmered form of the value of the current input field.

    0 讨论(0)
  • 2021-02-11 03:54

    You can do this by checking if key is space and selection start is 0 as below:

    $(function() {
      $('body').on('keydown', '#test', function(e) {
        console.log(this.value);
        if (e.which === 32 &&  e.target.selectionStart === 0) {
          return false;
        }  
      });
    });
    

    Demo Link

    0 讨论(0)
提交回复
热议问题