liam
liam

Reputation: 27

Add multiple select options to url paramter with Javascript

I'm looking to have a blog style page with multiple drop down filters. When a user changes I want to do an onChange event adding a parameter to the URL which would then adjust the content. I'd love to do this with AJAX but I want to get this bit functioning first.

Here is the basic form:

<form action="" method="GET">
    <select name="channel">
            <option value="" selected>Choose Channel</option>
            <option value="facebook-ads">Facebook ads</option>
            <option value="instagram-ads">Instagram ads</option>
    </select>
        <select name="brand">
            <option value="" selected>Choose Brand</option>
            <option value="brand-1">brand 1</option>
        </select>
</form>

When it was one selet I just used the inline onchange event.

I'm looking for the url to change to an example like this:

exampleurl.com/blog/?channel=facebook-ads&brand=brand-1

I want to be able to have a script that would allow either one or both to be added to the URL when the value is selected. I don't want to use a submit button.

So if there is already a parameter in the URL and the user selects a value from the other dropdown, then that parameter would be added to the URL and won't remove the other value.

Really hoping someone can help me with this as after a day of searching and trying, I'm still no further.

Upvotes: 0

Views: 1323

Answers (1)

coldgas
coldgas

Reputation: 83

Simple solution for your needs:

<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>

Upvotes: 1

Related Questions