Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select box to change url

I want to use a select to change the query on the end of a url to change it's sort options. e.g:

<select id="sort"> 
    <option value="?order_by=date">Recent</option> 
    <option value="?order_by=random">Popular</option>
    <option value="?order_by=random">Random</option> 
    <option value="">Staff Picks</option>
</select>

so for example by default a list of posts will be shown by date and then if a user chooses an option it will reload the page with the query string on the end of the URL. If possible looking to use jQuery to achieve this. Thanks.

like image 746
Cameron Avatar asked Jan 29 '26 17:01

Cameron


1 Answers

Attach a handler to the change event for the select box that adds the value of the selected option to the current window location with everything after the ? snipped off:

$('#sort').change(function(e){
    var locAppend = $(this).find('option:selected').val(),
        locSnip   = window.location.href.split('?')[0];

    window.location.href = locSnip + locAppend;
});

Here's an example ࢐ (it doesn't redirect, but you get the idea...)


To have the appropriate value selected on page load, you can run the following function before you bind the change handler:

function selectCurSort() {
    var match = window.location.href.split('?')[1];
    $('#sort').find('option[value$="'+match+'"]').attr('selected',true);
}
selectCurSort();
like image 109
mVChr Avatar answered Jan 31 '26 08:01

mVChr