EamonnMcElroy EamonnMcElroy - 3 months ago 22
jQuery Question

Guaranteed method of stripping leading/trailing spaces from form input

I am attempting to ensure that all leading and trailing spaces are removed from a form. The issue arose as a user entered an email address with a space and when they attempted to log in with this email address it wasnt accepted. I understand there are ways to do this via the server side but was looking a quick fix. I therefore used this piece of code:

$("input").change(function()
{
this.value=$(this).val().trim();
});


I want to know if anyone can see an instance where this will not work, such as a person filling an input and hitting enter rather than tabbing to or clicking the next input.

Answer

You can trim the input on form submit.

  
   $('input').blur(function(){
       this.value=$(this).val().trim();
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text"><br><br>
  <input type="text"><br><br>
  <input type="submit" value="submit">
</form>