tags:

views:

121

answers:

1

Hi

I am using the jquery .serializeArray() function and I send it to the server and that works all good.However I need to update a couple things on the client side that are serialized.

So instead of doing another selector on the textbox I want to just grab it out of the serialized array.

I am not sure how to do this

Product=Test&Qty=50

So say if I have something like this. I can I do something like this

 var sendFormData = form.serializeArray();
 var val = sendFormData["Product"].value;

but this seems not to work. I only can get it to work when I do something like this

 var sendFormData = form.serializeArray();
 var val = sendFormData[0].value;

I really don't want to do it by index since that means if the order changes the values could be all wrong. If you could do it by like keyname then that would not be a problem.

A: 

You can loop through the object, set what you want, then convert it to a parameter string if needed using $.param() (.serialize() does this internally), like this:

var arr = $("form").serializeArray();
$.each(arr, function(i, fd) {
    if(fd.name === "Product") fd.value = "New Value";
});    
var sendFormData = $.param(arr); //turn it into Product=Test&Qty=50 string format
//sendFormData == "Product=New+Value&Qty=50"

You can see a demo here

If you don't need to serialize it to a string, just simplify it a bit, like this:

var sendFormData = $("form").serializeArray();
$.each(sendFormData , function(i, fd) {
    if(fd.name === "Product") fd.value = "New Value";
});
//sendFormData == "Product=New+Value&Qty=50"
Nick Craver
I guess the question is what is faster to do then? do a selector on each of the boxes again or go through it with a each loop. I am guessing it is going through the loop?
chobo2
@chobo2 - If the boxes have an ID that's pretty fast, but unless you're submitting a *lot* of fields, the performance difference is going to be negligible either way....we're talking a *very* small amount of time spent either way here.
Nick Craver
so what would you recommend then? In the long wrong what would be the best way to go?
chobo2
@chobo2 - If you want the form to show the changed values and you're not redirecting the page, do the selector approach `$("input[name='Product']").val("new value");`, if you need to change multiple values and don't need them in the form, I'd do them in a loop like I have above, just for the sake of clean/centralized code.
Nick Craver
ya they get put back in a table.
chobo2