Christian
Christian

Reputation: 3972

serialize from a table element and not the whole form

Trying to serialize just the elements from a specific table but it only returns a result if i do the whole Form

in the below code, i want to ajax just the elements in tbl2

<form>
 <input type="text" id="tb1" name="tbl1"/>
  <table name="tbl1">
   <tr><td><input type="text" name="tb2"/></td></tr>
 </table>
 <table name="tbl2">
   <tr><td><input type="text" name="tb3"/></td></tr>
   <tr><td><input type="text" name="tb4"/></td></tr>
 </table>
</form>

the code

var params = $("#tbl2").serialize();

var resp = $.ajax({
    async: false,
    type: "POST",
    url: AppRoot + "webhandlers/postback.ashx",
    data: params
});

Upvotes: 11

Views: 35989

Answers (3)

Jayendra
Jayendra

Reputation: 52809

you can use the serializeArray method, which will give you the array of input fields and can be used with the data.

var params = $("#tbl2 input").serializeArray();

Upvotes: 1

Igor Serebryany
Igor Serebryany

Reputation: 3341

you cannot serialize a table -- that method doesn't apply to that kind of DOM object, only forms and form fields can be serialized.

if you really want to do what you're proposing, you need the proper selector to pick just the children of tbl2 that are also form elements, and then you'll have to serialize each one of those by hand. someone did it in another question, here: serialize without a form?

a better way might be to disable all the form elements that are NOT in the table you're interested in -- you'll need a selector to pick all form elements that are not child elements of tbl2 -- and THEN serialize the form. the disabled elements will be omitted.

Upvotes: 2

kapa
kapa

Reputation: 78751

First and foremost, a <table> cannot have a name attribute, and even if it could, the jQuery ID selector (#) would not match it.

If you use id instead (<table id="tbl2">), it will work like this:

var params = $("#tbl2 :input").serialize();

The :input selector selects all the form elements (here, inside #tbl2), it is needed because serialize() will only work on those.

Please also check out my jsFiddle Demo.

Upvotes: 23

Related Questions