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?

6
  • How can the user input if the inputs 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 Commented Jul 29, 2018 at 6:01
  • <input type="hidden" name="Id" value="83,85,70" /> and then you can split it in js and/or server side . Commented Jul 29, 2018 at 6:11
  • @Ashraf I want the value input by user. I have add more detail to my problem. Commented Jul 29, 2018 at 6:13
  • But how are you sending the data and to what file format? Are you using a default form POST action or using AJAX? Commented Jul 29, 2018 at 6:16
  • @NewToJS I tried using default form without success. I only able to send 1 data, instead of multiple data. Commented Jul 29, 2018 at 6:18

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

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 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 I've tried add JSON.stringify in the code, the printed result is the same. Still has comma separated.
@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 .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.