admin管理员组

文章数量:1415645

I have a form with a hidden field:

<input type="hidden" name="newdesc[]" id="newdesc" />

I have an autolookup and a plus button so the plus button adds the field value of the autolookup to an array:

newdesc_a.push(document.getElementById('autoplete1').value);
var x=document.getElementById("businesslist");
x.innerHTML=newdesc_a;
document.getElementById('newdesc').value = newdesc_a;

(newdesc_a is previously declared as an array)

It updates the div OK (businesslist) but does not assign the value to the newdesc.

I am sure it is simple but it is driving me mad!

I have a form with a hidden field:

<input type="hidden" name="newdesc[]" id="newdesc" />

I have an autolookup and a plus button so the plus button adds the field value of the autolookup to an array:

newdesc_a.push(document.getElementById('autoplete1').value);
var x=document.getElementById("businesslist");
x.innerHTML=newdesc_a;
document.getElementById('newdesc').value = newdesc_a;

(newdesc_a is previously declared as an array)

It updates the div OK (businesslist) but does not assign the value to the newdesc.

I am sure it is simple but it is driving me mad!

Share Improve this question asked Oct 23, 2012 at 10:46 Jim ElliottJim Elliott 371 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Given the name="newdesc[]" attribute, I assume PHP on the server side. When you submit a key two or more times, only the last value is available in the script via $_REQUEST. In the case of a key ending with [] , instead, PHP builds an array and make it available to your script via $_REQUEST['key']. Note that this behavior is application-specific, there's nothing like an array at the HTTP level.

Now, you want to pass an array from the client side (Javascript) to the backend (PHP). You have two options:

  1. Use a proprietary format, eg separate values by mas or colons, and split the string on the server side (or you can use an existing format like JSON, XML, ...)

  2. Take advantage of the PHP syntax for passing arrays

It seems you want to adopt the 2nd way, so you will want to submit a form like the following

<input name="email[]" value="[email protected]" />
<input name="email[]" value="[email protected]" />
<input name="email[]" value="[email protected]" />

PHP will be able to access a plain array in $_REQUEST if you build your form like this. Now, you have the problem of building the form programmatically on demand. This is the best I can think of (jQuery):

var email = $("#autoplete").value;

// if you really need to keep emails in an array, just
// emails.push(email);

$('<input type="hidden">').attr({
    name: 'email[]',
    value: email
}).appendTo('#myForm');

You want to assign a particular value of array to that element?

You can use like this.

document.getElementById('newdesc').value = newdesc_a.index;

where 'index' is the index of array. replace it.

本文标签: javascript add array item to form valueStack Overflow