0

I want to add query parameter to URL when user select from drop down

I have a list of sort values in <select></select>

<div class="filter-select">
    <select id="orders-filter" onchange="sortOrders(this.value)">
        <option value="" disabled selected>Sort order by</option>
        <option name="sortBy" value="sort=ordered">Ordered</option>
        <option name="sortBy" value="sort=approved">Approved</option>
        <option name="sortBy" value="sort=processing">Processing</option>
    </select>
</div>

Initially the URL will be having a default parameter and i want to add-on new parameter to URL

http://localhost:8000/manager/orders?outlet_id=1

function sortOrders(parameter) {
    var url = window.location.href;  

    if (url.indexOf('?') > -1) {
        if(url.indexOf('sort') > -1) {

        }
       url += '&'+parameter;
    } else {
       url += '?'+parameter;
    }

    window.location.href = url;
}

The above function works fine but when i select a different parameter it keeps adding it, i want to replace the current one

//current result
http://localhost:8000/manager/orders?outlet_id=1&sort=ordered&sort=approved&sort=processing

//expected result
http://localhost:8000/manager/orders?outlet_id=1&sort=ordered

http://localhost:8000/manager/orders?outlet_id=1&sort=approved

http://localhost:8000/manager/orders?outlet_id=1&sort=processing

I wan tot check if the parameter has sort keyword and replace the value if not append the parameter

thank you

Mr Robot
  • 847
  • 3
  • 17
  • 40

0 Answers0