Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Update query string value with Javascript (author: Anthony Vipond)
<select class="filter">
<option>Results Shown</option>
<option>20</option>
<option>30</option>
<option>50</option>
<option>100</option>
</select>
<script>
// This example is for a 'Results per page' dropdown
// It will check if this query string var exists, if not, it adds it
// If is exists, and its the same as the options text value, it does nothing
// If it exists and is different than the option text value, we redirect whilst updating query string value
// this function not written by me :)
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Change results shown per page
$('select.filter').change(function() {
var text = $(this).find(":selected").text();
if (location.search) {
var limit = getParameterByName('limit');
if (/[?&]limit=/.test(location.href)) {
if (limit !== text) {
location = location.search.replace('limit=' + limit, 'limit=' + text);
}
}
} else {
location.pathname + '?limit=' + text;
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment