How can trim spaces in all inputs without adding methods or classes?

后端 未结 3 857
离开以前
离开以前 2021-01-07 07:29

I\'m trying to remove blank spaces from the begining and ending of inputs in general without adding a class or id or event

I tried this live demo but is using

相关标签:
3条回答
  • 2021-01-07 07:34

    try $.trim on change input with type text:-

    jQuery

    $(function(){
        $('input[type="text"]').change(function(){
            this.value = $.trim(this.value);
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <p>Search1: <input type="text"/></p>
    <p>Search2: <input type="text"/></p>
    <p>Search3: <input type="text"/></p>
    <p>Search4: <input type="text"/></p>
    <p>Search5: <input type="text"/></p>

    Vanilla

    window.onload = function() {
      var inputs = document.getElementsByTagName('input');
      for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'text') {
          inputs[i].onchange = function() {
            this.value = this.value.replace(/^\s+/, '').replace(/\s+$/, '');
          };
        }
      }
    }
    <p>Search1: <input type="text"/></p>
    <p>Search2: <input type="text"/></p>
    <p>Search3: <input type="text"/></p>
    <p>Search4: <input type="text"/></p>
    <p>Search5: <input type="text"/></p>

    0 讨论(0)
  • 2021-01-07 07:51

    Try this:

    function trim(el) {
        var trimmedValue = el.val().trim();
        el.val(trimmedValue);
    }
    

    Your syntax for .trim() is wrong. To trim a input's value you don't need any regex, just try to change this:

    $(.input).text().trim();
    

    to this:

    $('input').val().trim();
    

    input is not a class, so you don't have to put the dot before it. Then you have to include it inside ' '. The value of an input is given by val() method, not text().

    This will only trim the input's value, you have to use this inside a function in order to make it works properly, as in the example above.

    0 讨论(0)
  • 2021-01-07 07:51

    This is one of the easiest way i found :), it uses jquery hope it helps, it uses your function The input have to be only:

    <input type="text" name="name">
    

    This automatically change all inputs, or you can asign to a class

    function trim_text(el) {
        el.value = el.value.
        replace(/(^\s*)|(\s*$)/gi, ""). // removes leading and trailing spaces
        replace(/[ ]{2,}/gi, " "). // replaces multiple spaces with one space
        replace(/\n +/, "\n"); // Removes spaces after newlines
        return;
    }
    $(function(){
      $("textarea").change(function() {
        trim_text(this);
      });
    
      $("input").change(function() {
        trim_text(this);
      });
    });
    
    0 讨论(0)
提交回复
热议问题