开发者

Select box to change url

开发者 https://www.devze.com 2023-02-17 20:03 出处:网络
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\">

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 th开发者_开发问答e URL. If possible looking to use jQuery to achieve this. Thanks.


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();


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.


Like this?

$("#sort").change(function(){
  window.location = $(this).find("option:selected").val();
});


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.


$(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.

0

精彩评论

暂无评论...
验证码 换一张
取 消