Need to crop all elements in the form using javascript

I need to trim all trailing white spaces from the text elements of the form. I need to do this with a minimum number of steps. As soon as I click onsubmit, it should trim all spaces and then perform further operations. Is there a script? If not, you can help me achieve my goal. Currently, I need to manually identify each item, and then do a similar cropping.

var username = myform.elements['username'].value; username.trim(); 

How to generalize it?

+6
source share
4 answers
  $("form").children().each(function(){ this.value=$(this).val().trim(); }) 

will clip all text fields and textarea inside the form tag, but not write unnecessary code inside the form.

+4
source
 $('input').val(function(_, value) { return $.trim(value); }); 
+12
source

Using

 var allInputs = $(":input"); 

to get all the elements of the form. Iterates using each function and truncates it.

It will be something like this (not verified)

 var allInputs = $(":input"); allInputs.each(function() { $(this).val($.trim($(this).val())); }); 
+2
source
 $('#yourformid').submit(function(){ $(':input').each(function(){ $(this).val($.trim($(this).val())) }) return true; }); 
+2
source

Source: https://habr.com/ru/post/918342/


All Articles