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

11,176

Solution 1

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

Solution 2

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.

Share:
11,176
Lado Lomidze
Author by

Lado Lomidze

What Would You Like To Know About Me?

Updated on June 25, 2022

Comments

  • Lado Lomidze
    Lado Lomidze almost 2 years

    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/foyetolo/2/edit

    It works only when you hit spacebar for first time. When you start typing other characters and select whole text in input (ctrl+a) and then hit the space bar it adds the space in the beginning of input field.

    So, how to check if on keypress/keydown if the first character will be a space, return false and not allow it to type the space as a first character?

  • Lado Lomidze
    Lado Lomidze about 10 years
    I forgot to mention that in my case I was not suppose to use trim or keyup.