AlexioVay
AlexioVay

Reputation: 4527

Trim strings before using map?

I want to get all input values from a page a user has made and want to store it in an array to make an ajax-call to process the data. I'm doing it this way:

$('#save').click(function(){
    var data = $('*[data-array]').map(function(idx, elem) {
    $.trim(elem);
    return $(elem).val();
    }).get();

The problem is that it won't trim strings before creating this array. It seems $.trim doesn't apply? For example if I type ABC____________ (_ being whitespace, have to write it here to show you the whitespace as demonstration) I'll get the result: ABC_ (with one whitespace after ABC)

Upvotes: 2

Views: 173

Answers (2)

AmmarCSE
AmmarCSE

Reputation: 30557

You have to trim the value

$('#save').click(function(){
    var data = $('*[data-array]').map(function(idx, elem) {
    $(elem).val($.trim($(elem).val()));
    return $(elem).val();
    }).get();

 $('#save').click(function(){
        var data = $('*[data-array]').map(function(idx, elem) {
        $(elem).val($.trim($(elem).val()));
        return $(elem).val();
        }).get()
        
        console.log(data);
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input data-array/>
<input data-array/>
<input data-array/>
<input type="button" id="save" value="save"/>

Upvotes: 4

Satpal
Satpal

Reputation: 133403

$.trim() return you trimmed string, it doesn't modifies the the supplied string

var el = $(elem);
var value = $.trim(el.val());
el.val(value );
return value;

Upvotes: 2

Related Questions