WraithLux
WraithLux

Reputation: 699

Fetch data from form and build a multidimensional array of it

I have a simple html form that is structured something like this:

<form name="test" action="">
    <tr class="selectable" data-selected=false>
        <input type="hidden" name="product[gate][id] value=<? echo $pid?>"/>
        <input type="text" name="product[gate][amount]"/> 
    </tr>
</form>

I need to collect each tr row that has "data-selected" true.

So that I would end up with some sort of an array that I could then send to server with jQuery POST request.

Something like this:

products => Array(
    [0] => Array(
        id => 1134,
        amount => 2
    ),
    [2] => Array(
        id => 1134,
        amount => 3
    )
)

I don't know how to build a multidimensional array with js, I am not at all familiar with JS objects or JSON, either. What is the easiest way to do this?

Upvotes: 0

Views: 1234

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Try this:

var $trs = $("tr").filter(function() {
    return $(this).data("selected");
});

var products = [];
$.each($trs, function(i, $tr) {
    products.push({
        "id": $('input[type="hidden"]', $tr).val(),
        "amount": $('input[type="text"]', $tr).val()
    });
})

Example fiddle

The products variable should then be in a format you can use in an AJAX call. You may want to use nicer selectors than input[attr], a class for example, in your working code.

Upvotes: 1

codef0rmer
codef0rmer

Reputation: 10520

I assume that you have the necessary data within your form tag. If any data you do not want to post then it should not be inside <form>.

$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

More info : http://api.jquery.com/serialize/

Upvotes: 1

Related Questions