jeph perro
jeph perro

Reputation: 6432

How to push name value objects into an array?

I'm trying to implement a little ajax form using jQuery.

My simplified form looks something like this, I gave all the inputs and textareas the class="form_one_inputs" :

<form action="myform" id="form_one" method="post" >
     <div class="formleft">
          <p>Name</p>
     </div>
     <div class="formright">
          <input name="name" type="text" class="form_one_inputs" ></div>
     </div>
 ...
           <input id="email" maxlength="45" name="email" class="form_one_inputs" type="email">
 ...
           <textarea id="Comments" name="Comments" class="form_one_inputs" >
 ...

In my jquery function, I can make my ajax submit work if I put all the form data into this object:

 var formData = {
    'name'      : $('input[name=name]').val(),
    'email'     : $('input[name=email]').val(),
    'Comments'  : $('textarea[name=Comments]').val(),
    'subject'   : $('input[name=subject]').val()
  };

I can loop through all the inputs and textareas like this :

$('.form_one_inputs').each(function(index, obj){
     alert(index + " : " + obj.value +  ":" + obj.name);
     //
     // need to add each input to formData object
 });

How can I generalize my code to put all the elements of class="form_one_inputs" into the formData object. I've been trying, but not succeeding with formData.push()

Upvotes: 0

Views: 3242

Answers (6)

Ragnar
Ragnar

Reputation: 4578

Try this way:

$('.form_one_inputs').each(function(){
    var item = $(this);
    alert("name:" + item.attr('name') + " value:" + item.val());
 });

to add all items to formData object use this way:

var formData = {}; 
$('.form_one_inputs').each(function(){
    var item = $(this);
    formData[item.attr('name')] = item.val();
 });

if you want to serialize all elements in the form to JSON format, use this function:

var jsonSerializer = function (form) {
    var data = {};
    var items = form.serializeArray();
    for (var i = 0; i < items.length; i++)
       data[items[i].name] = items[i].value;
       return data;
};

var formData = jsonSerializer($('form'));

in that way you don't need to know the names of the inputs

Upvotes: 2

Yordis Prieto Lazo
Yordis Prieto Lazo

Reputation: 850

You are trying to use push. Push is for arrays. In your case you need to create a hash where the key is the name of the input and the value is the value of the input.

var formData = {};
$('.form_one_inputs').each(function(index, obj){
  formData[obj.name] = obj.value
});

Did you try to use form serialization?

Upvotes: 0

Martin Da Rosa
Martin Da Rosa

Reputation: 452

(function($){
    $.fn.serializeObject = function(){

        var self = this,
            json = {},
            push_counters = {},
            patterns = {
                "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                "key":      /[a-zA-Z0-9_]+|(?=\[\])/g,
                "push":     /^$/,
                "fixed":    /^\d+$/,
                "named":    /^[a-zA-Z0-9_]+$/
            };


        this.build = function(base, key, value){
            base[key] = value;
            return base;
        };

        this.push_counter = function(key){
            if(push_counters[key] === undefined){
                push_counters[key] = 0;
            }
            return push_counters[key]++;
        };

        $.each($(this).serializeArray(), function(){

            // skip invalid keys
            if(!patterns.validate.test(this.name)){
                return;
            }

            var k,
                keys = this.name.match(patterns.key),
                merge = this.value,
                reverse_key = this.name;

            while((k = keys.pop()) !== undefined){

                // adjust reverse_key
                reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

                // push
                if(k.match(patterns.push)){
                    merge = self.build({}, self.push_counter(reverse_key), merge);
                }

                // fixed
                else if(k.match(patterns.fixed)){
                    merge = self.build({}, k, merge);
                }

                // named
                else if(k.match(patterns.named)){
                    merge = self.build({}, k, merge);
                }
            }

            json = $.extend(true, json, merge);
        });

        return json;
    };
})(jQuery);

var myobj = $('.form_one_inputs').serializeObject();

...

Upvotes: 0

user2699477
user2699477

Reputation:

$('.form_one_inputs').each(function(index, obj){
     formData[obj.name] = obj.value;
 });

Like this?

Upvotes: 0

tpdietz
tpdietz

Reputation: 1368

Try this code:

$('.form_one_inputs').each(function(index, obj){
     alert(index + " : " + obj.value +  ":" + obj.name);
     formData.append(obj.name, obj.value);
 });

Upvotes: 0

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

var formData = {};
$('.form_one_inputs').each(function(){
    var $this = $(this);
    formData[$this.attr('name')] = $this.val();
});

Keep in my this won't work for all input types (ie those that don't use val());

Upvotes: 0

Related Questions