Skip to content

Instantly share code, notes, and snippets.

@thewinterwind
Last active December 27, 2015 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thewinterwind/7290788 to your computer and use it in GitHub Desktop.
Save thewinterwind/7290788 to your computer and use it in GitHub Desktop.
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