Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  103] [ 1]  / answers: 1 / hits: 32312  / 9 Years ago, thu, november 12, 2015, 12:00:00

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

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


Thanks in advance.


More From » jquery

 Answers
25

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>




[#64412] Tuesday, November 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anitadevonm

Total Points: 730
Total Questions: 93
Total Answers: 74

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;