如何在不添加方法或类的情况下修剪所有输入中的空格?

Car*_*les 0 javascript jquery

我试图从输入的开始和结束中删除空格,而不添加类或id或事件

我试过这个现场演示但是正在使用onchange事件

<javascript>
  function trim(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;
  }
</script>
<p>Search1: <input type="text" onchange="return trim(this)" /></p>
<p>Search2: <input type="text" onchange="return trim(this)" /></p>
<p>Search3: <input type="text" onchange="return trim(this)" /></p>
<p>Search4: <input type="text" onchange="return trim(this)" /></p>
<p>Search5: <input type="text" onchange="return trim(this)" /></p>
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我如何使我的所有输入修剪输入值(CSS或JAVASCRIPT)像这样:

 <script>
   Here in this script will trim blank spaces starting or ending so don't need to add anything in the input
 </script> 
 <input type="text" />
Run Code Online (Sandbox Code Playgroud)

我尝试了这个但是没有用

 $(.input).text().trim()
Run Code Online (Sandbox Code Playgroud)

请有人可以帮帮我吗?

提前致谢.

Ben*_*enG 7

尝试$.trimchange同类型的文本输入: -

jQuery的

$(function(){
    $('input[type="text"]').change(function(){
        this.value = $.trim(this.value);
    });
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

香草

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+$/, '');
      };
    }
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)