jquery - Trim leading and trailing spaces on "on focus out"

Imagine I have a HTML form with a lot of text fields

<input id="name" type="text" required>
<input id="surname" type="text" required>
<input id="address" type="text" required>

How to trim leading and trailing spaces on all text fields "on focus out", i.e, when the user leaves filling the text field?

Upvotes: 0

Views: 2029

Answers (2)

Pankaj Shinde
Pankaj Shinde

Reputation: 3689

Simply

$(function () {
    $("input[type=text]").blur(function () {
        $(this).val($(this).val().trim());
    });
});

Upvotes: 0

A simple solution is to use the jquery function $.trim

//removes leading and trailing spaces on every text field "on focus out"
$( ":text" ).each(function( index ) {
    $( this ).focusout(function() {
      var text = $(this).val();      
      text = $.trim(text);
      $(this).val(text);
    });
});

====================

Here is a simple code

//removes leading and trailing spaces on every text field "on focus out"
$( ":text" ).each(function( index ) {
    $( this ).focusout(function() {
      var text = $(this).val();      
      text = $.trim(text);
      $(this).val(text);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First Name<br>
<input id="name" type="text" required><br>
Surname<br>
<input id="surname" type="text" required><br>
Address<br>
<input id="address" type="text" required><br>

Upvotes: 2

Related Questions