Search code examples
javascriptjqueryarraystrim

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)


Solution

  • 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"/>