Disable spaces in Input, AND allow back arrow?

后端 未结 4 957
感动是毒
感动是毒 2020-11-30 09:02

I am trying to disable spaces in the Username text field, however my code disables using the back arrow too. Any way to allow the back arrow also?

    $(func         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 09:32

    Try checking for the proper key code in your function:

    $(function(){
        var txt = $("input#UserName");
        var func = function(e) {
          if(e.keyCode === 32){
            txt.val(txt.val().replace(/\s/g, ''));
          }
        }
        txt.keyup(func).blur(func);
    });
    

    That way only the keyCode of 32 (a space) calls the replace function. This will allow the other keypress events to get through. Depending on comparability in IE, you may need to check whether e exists, use e.which, or perhaps use the global window.event object. There are many question on here that cover such topics though.

    If you're unsure about a certain keyCode try this helpful site.

提交回复
热议问题