如何在不增加方法或类的情况下修剪所有输入中的空格? [英] How can trim spaces in all inputs without adding methods or classes?

查看:89
本文介绍了如何在不增加方法或类的情况下修剪所有输入中的空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从输入的开头和结尾删除空格,而通常不添加类,id或事件

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

我尝试了这个实时演示,但是正在使用 onchange事件

I tried this live demo but is using onchange event

<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>

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

Somebody can help me about how to make all my inputs trim input values (CSS OR JAVASCRIPT) like this:

 <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" />

我尝试了这个,但是没有用

I tried this but is not working

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

请有人可以帮助我吗?.

Please somebody can help me?.

谢谢.

推荐答案

change输入文本上输入$.trim尝试:-

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>

香草

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>

这篇关于如何在不增加方法或类的情况下修剪所有输入中的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆