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.

Related posts

Leave a Reply

5 comments

  1. 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();
    
  2. I’m not quite sure why you aren’t just using something like:

    <form method="GET">
        <input type="hidden" name="query" value="..." />
    
        <select id="sort" name="order_by">
            <option value="date">Recent</option>
            <option value="popular">Popular</option>
            <option value="random">Random</option>
            <option value="staff">Staff Picks</option>
        </select>
    
        <input type="submit" value="Sort" />
    </form>
    

    And, for the JS, if any, just:

    $('#sort').change(function() {
        $(this).parents('form').submit();
    });
    

    Then, you don’t require anyone to have JavaScript enabled.

  3. Add

    onchange="if (this.value && /^?/.test(this.value)) location = location.path + this.value"
    

    to your <select>.

    You might want to put a blank option at the top too.

  4. $(function() {
       $("#sort").change(function() {
         var myVal = $(this).val();
         window.location = "www.mywebsite.com/"+ myVal;
       });
       var qs = window.location.pathname;
       $("#sort option").each(function() {
           if(qs.contains($(this).val()))
            $(this).addAttr("selected","selected");
        });
    });
    

    Try that.