Last active
December 27, 2015 07:39
-
-
Save thewinterwind/7290788 to your computer and use it in GitHub Desktop.
Update query string value with Javascript (author: Anthony Vipond)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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