Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use jQuery's serialize form fields and trim the value in the fields?

I have a form that uses jQuery to submit an ajax post and it serializes the form that is sent up. The code looks like this:

var form = $("form");
var action = form.attr("action");
var serializedForm = form.serialize();
$.post(action, serializedForm, function(data)
{
  ...
});

The problem here is that if a field has trailing white space, the serialize function will turn those spaces to plus (+) signs, when they should be stripped.

Is there a way to get the fields trimmed without doing the following:

$("#name").val( jQuery.trim( $("#name") ) );
like image 334
Jared Avatar asked Dec 01 '22 13:12

Jared


2 Answers

You could try looping through the object and triming everything.

//Serialize form as array
var serializedForm = form.serializeArray();
//trim values
for(var i =0, len = serializedForm.length;i<len;i++){
  serializedForm[i] = $.trim(serializedForm[i]);
}
//turn it into a string if you wish
serializedForm = $.param(serializedForm);
like image 178
Jethro Larson Avatar answered Dec 04 '22 09:12

Jethro Larson


Trim all <input> and <textarea></textarea> element values in the DOM:

$('input, textarea').each(function(){
    $(this).val(jQuery.trim($(this).val()));
});
like image 45
micahwittman Avatar answered Dec 04 '22 10:12

micahwittman