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

前端 未结 3 1705
耶瑟儿~
耶瑟儿~ 2021-02-11 03:29

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

3条回答
  •  星月不相逢
    2021-02-11 03:46

    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

提交回复
热议问题