Krishna Shetty
Krishna Shetty

Reputation: 1441

How to retrieve array of value by name using jQuery?

I have a HTML as below. Please tell me how can I retrieve the value 'task' array in jQuery.

<div class="column1">
<input class="task_name" type="text" placeholder="Enter task name.." value="" name="task[0][name]">
</div>
<div class="column2">
<select class="task_ppl_required" name="task[0][number]">
    <option selected="selected">1</option>
    <option>2</option>
</select>
<input class="task_id" type="hidden" value="0" name="task[0][guid]">
</div>
<div class="column1">
<input class="task_name" type="text" placeholder="Enter task name.." value="" name="task[2][name]">
</div>
<div class="column2">
<select class="volunteer_task_ppl_required" name="task[2][number]" value="1">
<option selected="selected">1</option>
<option>2</option>
</select>
<input class="task_id" type="hidden" value="0" name="task[2][guid]">
</div>

Upvotes: 0

Views: 908

Answers (3)

Bergi
Bergi

Reputation: 665456

function getValues(form) {
    var vals = {};
    form.find("[name]").each(function() {
        var names = this.name.split(/[[\]]+/);
        if (names[names.length-1] == "") names.pop();
        var obj = vals;
        for (var i=0; i<names.length-1; i++) {
            if (! (names[i] in obj))
                obj[names[i]] = {};
            obj = obj[names[i]];
        }
        obj[names[i]] = this.value;
    });
    return vals;
}

Instead of .find("[name]") you also could just use .serializeArray(), which might be more exact and allow more inputs. Now, you can

> getValues($myForm).task[0]
{number: "1", guid: "0"}

(Demo at jsfiddle.net, more sophisticated using Array.reduce)

Upvotes: 1

charlietfl
charlietfl

Reputation: 171700

If you want all the values of form in order to send to server you can simply use jQuery serialize() method

var formVals= $('##myForm').serialize();

This gets sent to server using jQuery AJAX in folloing manner:

$.post( url, formVals, function(){/* success code*/});

Reference: http://api.jquery.com/serialize/

Upvotes: 1

kumiau
kumiau

Reputation: 724

The array aproximation works well in PHP, where you receive the form values on the $_POST variable and if the syntax match (as yours in the example) he would construct an array with the elements.

You could use jQuery serializeArray. From the site:

The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements.

Upvotes: 1

Related Questions