1

My problem is similar to the link below: similar problem

I would like to send multiple values using form and javascript. Instead fixed value like code below:

<input type="hidden" name="Id[]" value="83" />
<input type="hidden" name="Id[]" value="85" />

I would like the value is based on user input. How can I achieve this?

I have other code to input user input

Link name: <input type='text' id='linkid'>
<button onclick="saveLink();return false">Save link</button>

And javascript code

var idarray=[];

function saveLink() {
   var id = document.getElementById("linkid").value;
   idarray.push(id);
}

How to send this idarray using html form?

roscoe_x
  • 609
  • 1
  • 9
  • 16
  • How can the user input if the `input`s are hidden and how would you like to send the data and what would you like to send it to? Too much relevant information is missing from your question description – NewToJS Jul 29 '18 at 06:01
  • `` and then you can split it in js and/or server side . – Ashraf Jul 29 '18 at 06:11
  • @Ashraf I want the value input by user. I have add more detail to my problem. – roscoe_x Jul 29 '18 at 06:13
  • But how are you sending the data and to what file format? Are you using a default `form` POST action or using `AJAX`? – NewToJS Jul 29 '18 at 06:16
  • @NewToJS I tried using default form without success. I only able to send 1 data, instead of multiple data. – roscoe_x Jul 29 '18 at 06:18
  • Possible duplicate : https://stackoverflow.com/a/5035796/1140136 – Ashraf Jul 29 '18 at 06:19

1 Answers1

2

Assign the id to hidden element and set the value to this element before form submit.

Here is a working snippet:

var idarray=[];

function saveLink() {
   var id = document.getElementById("linkid").value;
   idarray.push(id);
   console.log(idarray);
   document.getElementById("someid").value=idarray;
   console.log(document.getElementById("someid").value);
  
}

 //document.getElementById("someid").value=idarray;
 //document.forms[0].submit();
<input type="hidden" id="someid" name="Id[]" value="" />


Link name: <input type='text' id='linkid'>
<button onclick="saveLink();return false">Save link</button>
NullPointer
  • 7,094
  • 5
  • 27
  • 41
  • Thank you @NullPointer. It worked. I still have some problem with the PHP receiving code though. Instead of separated data, I have comma separated multiple data. I'll check on it first. – roscoe_x Jul 29 '18 at 06:44
  • @roscoe_x Its not recommended to consider comma separation , for a simple reason : what if one of the URLs had comma in its text ? . Dealing with JSON object is way better . – Ashraf Jul 29 '18 at 07:45
  • @Ashraf I've tried add JSON.stringify in the code, the printed result is the same. Still has comma separated. – roscoe_x Jul 29 '18 at 11:15
  • @roscoe_x Yep , but in case one or more URLs has a comma the JSON will take care of it and wrap it in a way that doesn't affect the process . The classical approach doesn't . – Ashraf Jul 30 '18 at 03:35