@darion
To pass an array from a form into a URL using JavaScript, you can follow these steps:
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.