0

Trying to do very simple thing.

Have too many of these fields:

<input name="itempriceqty0" /><input name="itemprice0" /><br />
<input name="itempriceqty1" /><input name="itemprice1" /><br />
<input name="itempriceqty2" /><input name="itemprice2" /><br />

etc...

Goal is to get their values in one PHP string of this format: itempriceqty0=itemprice0, itempriceqty1=itemprice1,itempriceqty2=itemprice3,etc...

Serializing with jquery gives a url formatted string, which I need to split many times with PHP to get rid of input names and other &= chars.

$.post('test.php', {
  itemprice: $('#itempricefieldswrapper :input').serialize() }, ...
);

What is the easiest way to handle it with jquery?

P.S. Googled everywhere. Need help. Thanks.

Alex G
  • 3,048
  • 10
  • 39
  • 78

3 Answers3

2

Something like this?

Give all your input elements to gather a class name, e.g. qty-input

Collect the values like this:

var values = '';
$('.qty-input').each(function(){
  values = values + this.name + '=' + this.value + ',' ;
});
Pelle
  • 6,423
  • 4
  • 33
  • 50
  • Thanks a lot. I guess each() is the only right way to go. var itempricevalues = ''; $('input[name^=itempriceqty]').each(function() { var num = $(this).attr('name').replace(/itempriceqty/, ''); itempricevalues = itempricevalues + this.value + '=' + $('input[name=itemprice'+num+']').val() + ','; }); – Alex G Nov 01 '11 at 11:12
0

You could look at json:

Convert form data to JavaScript object with jQuery

That post shows how you can read the form values into json and serialize it. You will need a json deserializer library in php of which im sure there's plenty to choose from.

(JSON: json_decode is built in right? Im not a php boi).

Community
  • 1
  • 1
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
  • If you have PHP 5.2.0 or greater, there is a built in [json_decode](http://php.net/manual/en/function.json-decode.php) function. – Janis Veinbergs Nov 01 '11 at 10:30
0

Do you know that you can use the following:

<input type="text" name="foo[]" value="field1" />
<input type="text" name="foo[]" value="field2" />

and then, if you do this:

var_dump($_POST['foo']);

you get:

array(2) {
  [0]=>
  string(6) "field1"
  [1]=>
  string(6) "field2"
}

I'm not sure if that's relevant to what you want but it seems like it might be.