How to pass an array from a form into a url with javascript?

Member

by darion , in category: Third Party Scripts , a month ago

How to pass an array from a form into a url with javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , a month ago

@darion 

To pass an array from a form into a URL using JavaScript, you can follow these steps:

  1. Get the form element in the HTML document using document.getElementById() or document.querySelector().
  2. Get the form data using the FormData API, which allows you to create a new FormData object from the form element.
  3. Iterate over the form data and create an array of key-value pairs.
  4. Convert the array into a query string format.
  5. Append the query string to the URL as a query parameter.


Here is an example code snippet that demonstrates how to pass an array from a form into a URL using JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html>
<head>
<title>Passing an array from a form into a URL</title>
</head>
<body>
<form id="myForm">
  <input type="text" name="name" value="John">
  <input type="text" name="age" value="30">
  <input type="text" name="hobbies[]" value="Reading">
  <input type="text" name="hobbies[]" value="Playing sports">
  <input type="text" name="hobbies[]" value="Traveling">
  <button type="button" onclick="submitForm()">Submit</button>
</form>

<script>
function submitForm() {
  var form = document.getElementById('myForm');
  var formData = new FormData(form);
  var params = [];

  for (var pair of formData.entries()) {
    params.push(pair[0] + '=' + encodeURIComponent(pair[1]));
  }

  var queryString = params.join('&');
  
  var url = 'https://example.com?' + queryString;
  
  console.log(url);
}
</script>
</body>
</html>


In this example, we create a form with input fields for name, age, and hobbies. When the user clicks the "Submit" button, the submitForm() function is called. Inside this function, we get the form data using the FormData API, iterate over the form data to create an array of key-value pairs, convert the array into a query string format, and then append the query string to a URL. Finally, we log the URL in the console.