Strip white spaces on input

前端 未结 4 642
一个人的身影
一个人的身影 2020-12-02 14:56

I have a field that does not need any white spaces. I need to remove any as they are entered. Here\'s what I\'m trying... no luck so far

$(\'#noSpacesField\'         


        
相关标签:
4条回答
  • 2020-12-02 15:33

    Use jQuery trim to remove leading and trailing white space

    $.trim(" test case "); // 'test case'
    

    To remove all whitespace...

    " test   ing  ".replace(/\s+/g, ''); // 'testing'
    

    To remove whitespace as it is entered...

    $(function(){
      $('#noSpacesField').bind('input', function(){
        $(this).val(function(_, v){
          return v.replace(/\s+/g, '');
        });
      });
    });
    

    Live Example

    0 讨论(0)
  • 2020-12-02 15:38

    If you only wanna put numbers, try this! :D

    $("#id").keyUp(function(){
       if(isNaN($(this).val())) {
         $(this).val(0);
       }
       $(this).val($(this).val().replace(/ +?/g, ''));
    })
    
    0 讨论(0)
  • 2020-12-02 15:47
    $('#noSpacesField').keyup(function() {
      $(this).val($(this).val().replace(/ +?/g, ''));
    });
    

    This will remove spaces as you type, and will also remove the tab char.

    0 讨论(0)
  • 2020-12-02 15:47

    We can achieve the desired outcome with pure javascript.

    Input

    <input type="text" id="whiteSP" onChange={ (e)=>removeSpace(e) } />
    

    Js Function

    function removeSpace(e){
        let val = (e.target.value).trim();
        console.log(val);
    }
    

    However on a form submit button clicked

    console.log( ( (" test case ").trim() ).replace(" ", "") )
    
    0 讨论(0)
提交回复
热议问题