0

I want to create a url where I send select option values to the url.

I already saw that article, which helps a lot. Add multiple select options to url paramter with Javascript

The only thing with this code is, if I choose the second option and leave the first blank, I get a name=undefined in the url for the first value. But only for the first option value, the others are just not in the url if blank.

Can you please help to adjust the code, thank you. if there is no value selected, it should be not added to the url.

Another point is, if the option is preselected with html, it gets ignored and therefor an undefined.

<option value="2" selected>2</option>

thank you for your help.

Here is the code/answer from the other article:

<form action="" method="GET" id="myForm">
    <select name="channel" id="0" onChange="changeURL(0)">
            <option value="" selected disabled>Choose Channel</option>
            <option value="facebook-ads">Facebook ads</option>
            <option value="instagram-ads">Instagram ads</option>
    </select>
        <select name="brand" id="1" onChange="changeURL(1)">
            <option value="" selected disabled>Choose Brand</option>
            <option value="brand-1">brand 1</option>
            <option value="brand-2">brand 2</option>
            <option value="brand-3">brand 3</option>
        </select>
</form>
<p id="test"></p>
<script>

var filters = [,]; // create an array with empty values (only 2 in this case)

function changeURL(a) {
    var yourUrl = "https://yourdomain.com"; // your url
    filters[a] = document.getElementById(a).value; // set the value of the selected filter inside the array
    var preFilter = "?"; // blank url will need a "?" to start with your filters
    for(var i=0; i<filters.length; i++) {
        aName = document.getElementById(i).name; // get the name of the filter
        yourUrl += preFilter + aName + "=" + filters[i];
        preFilter = "&";  
    }
    document.getElementById("test").innerHTML = yourUrl; // test output of the new url
}
</script>

2
  • What have you tried so far? You should add your code to the question. Commented Mar 22 at 6:13
  • Thank you for contributing to Stackoverflow's repository of questions. Consider improving the question by providing a minimal reproducible example directly in the question. Commented Mar 22 at 6:13

3 Answers 3

1

There is no need for constructing the querystring by hand. You can use the URLSearchParams object. So, first get the formData, parse that into a URLSearchParams, and toString it in the end.

document.forms.myForm.addEventListener('change', e => {
  let form = e.target.form;
  let data = new FormData(form);
  let params = new URLSearchParams(data);
  form.url.value = `https://yourdomain.com?${params.toString()}`;
});
<form action="" method="GET" id="myForm">
  <select name="channel">
    <option value="" selected disabled>Choose Channel</option>
    <option value="facebook-ads">Facebook ads</option>
    <option value="instagram-ads">Instagram ads</option>
  </select>
  <select name="brand">
    <option value="" selected disabled>Choose Brand</option>
    <option value="brand-1">brand 1</option>
    <option value="brand-2">brand 2</option>
    <option value="brand-3">brand 3</option>
  </select>
  <p><output name="url">https://yourdomain.com</output></p>
</form>

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

Comments

0

<form action="" method="GET" id="myForm">
    <select name="channel" id="0" onChange="changeURL()">
        <option value="" selected disabled>Choose Channel</option>
        <option value="facebook-ads">Facebook ads</option>
        <option value="instagram-ads">Instagram ads</option>
    </select>
    <select name="brand" id="1" onChange="changeURL()">
        <option value="" selected disabled>Choose Brand</option>
        <option value="brand-1">brand 1</option>
        <option value="brand-2">brand 2</option>
        <option value="brand-3">brand 3</option>
    </select>
</form>
<p id="test"></p>
<script>
// Initialize the filters array
var filters = [];

// Initialize filters with any pre-selected values on page load
document.addEventListener("DOMContentLoaded", function() {
    // Get all select elements
    var selects = document.querySelectorAll('select');
    
    // Initialize the filters array with the correct size
    filters = new Array(selects.length).fill("");
    
    // Check for any pre-selected options
    selects.forEach(function(select) {
        if (select.selectedIndex > 0) { // If something is selected (not the disabled option)
            filters[select.id] = select.value;
        }
    });
    
    // Update URL on initial load
    changeURL();
});

function changeURL() {
    var yourUrl = "https://yourdomain.com"; // Base URL
    var queryParams = [];
    
    // Update the current changed value
    var selects = document.querySelectorAll('select');
    selects.forEach(function(select) {
        filters[select.id] = select.value;
    });
    
    // Build query parameters, only including valid values
    selects.forEach(function(select) {
        var paramName = select.name;
        var paramValue = filters[select.id];
        
        // Only add to URL if there's a valid value
        if (paramValue && paramValue !== "" && paramValue !== "undefined") {
            queryParams.push(paramName + "=" + paramValue);
        }
    });
    
    // Add the query string if we have parameters
    if (queryParams.length > 0) {
        yourUrl += "?" + queryParams.join("&");
    }
    
    // Display the result
    document.getElementById("test").innerHTML = yourUrl;
}
</script>

Simple explanation:

It only includes the options you choose and puts them into the URL.

hope this helps.

4 Comments

Hi Ajoy, wow such a fast and good answer. That works, thank you so much!
Hi Ajoy, would it also be possible that I can choose brand 1 and brand 2? Thank you.
Yes, con can do that, first change Modify the <select> element for "brand": <select name="brand" id="1" onChange="changeURL()" multiple> second change inside the changeURL function start from the first Please visit think link for the updated changeURl function code, since it too long that's why I'm sharing the link pastebin.pl/view/1ec78bdd
Thank you! Is it possible that I can choose multipe options without pressing "strg"? Just by clicking? Like a checkbox listed as a dropdown menu? And that the option values are just joined: brand1,2
0

Here is a shorter alternative version:

<form action="" method="GET" id="myForm">
    <select name="channel">
            <option value="" selected disabled>Choose Channel</option>
            <option value="facebook-ads">Facebook ads</option>
            <option value="instagram-ads">Instagram ads</option>
    </select>
        <select name="brand">
            <option value="" selected disabled>Choose Brand</option>
            <option>brand 1</option>
            <option>brand 2</option>
            <option>brand 3</option>
        </select>
</form>
<p id="test"></p>
<script>
   const frm=document.forms[0];
   frm.addEventListener("change",_=>
     console.log("https://your domain.com?"+new URLSearchParams(new FormData(frm)).toString())
   );
</script>

1 Comment

Ah, @chrwahl was faster than me. 😄 Well done!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.