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

前端 未结 4 1264
萌比男神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: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

提交回复
热议问题