Reputation: 1539
Hi i want to refresh page on change of my select box value add this value to url as a query string here is my code
<select name="country_id" id="country" class="validate-select" title="Country">
<option value=""></option>
<option value="BH">Bahrain</option>
<option value="KW">Kuwait</option>
<option value="OM">Oman</option>
<option value="QA">Qatar</option>
<option value="SA">Saudi Arabia</option>
<option value="AE">United Arab Emirates</option>
</select>
And the JS code i wrote for this is
jQuery('#country').on('change', function () {
var url = window.location.href;
url += '?country='+jQuery(this).val()+''
window.location.href = url;
});
Its working fine but its always adding new param like this not replacing previous one
?country=KW?country=QA
I want to remove previous param before adding new one and refresh page.
Upvotes: 0
Views: 7294
Reputation: 1360
Try using window.location.search
you can update a param value or add a new param
jQuery('#country').change(function(){
query = 'country=' + $(this).val();
window.location.search = query;
});
Upvotes: 2
Reputation: 388
This will work for you
url+=url.split('?')[0]+jQuery(this).val()+'';
or you could alternatively declare your url var as url = window.location.host;
Upvotes: 0
Reputation: 5778
Replace window.location.href = url
to window.location=window.location.href + "?country=" + this.value
window.location.href
is just returns the href (URL) of the current page please find below snippet as well to understand
And for remove querystring from href you can add .split('?')[0]
after getting url like window.location.href.split('?')[0]
$(function(){
$("#country").change(function(){
debugger;
window.location=window.location.href.split('?')[0] + "?country=" + this.value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="country_id" id="country" class="validate-select" title="Country">
<option value=""></option>
<option value="BH">Bahrain</option>
<option value="KW">Kuwait</option>
<option value="OM">Oman</option>
<option value="QA">Qatar</option>
<option value="SA">Saudi Arabia</option>
<option value="AE">United Arab Emirates</option>
</select>
Upvotes: 2