Uidev123
Uidev123

Reputation: 83

Get browser url and append dropdown option value

I have created a dropdown for sorting items and on click of an option the page reload and display sorting result. Here is my code of dropdown

<div class="sorting-option">
<label for="selectdropdown">Sort by : </label>
<select id="selectdropdown" class="dropdown-select" name="selectdropdown">
<option value="&">Recommended Items</option>
<option value="&sort1desc=F&sort1=Item_NAME">Name (A-Z)</option>
<option value="&sort1desc=T&sort1=Item_NAME">Name (Z-A)</option>
<option value="&sort1desc=F&sort1=Item_ONLINECUSTOMERPRICE">Price (Low-High)  
</option>
<option value="&sort1desc=T&sort1=Item_ONLINECUSTOMERPRICE">Price (High-Low) 
</option>
</select>
</div>

What i am trying to achive is to append my option value in browser url and after that redirect to that url on clicking of dropdown option. For example my browser url is http://www.browserurl.com/?search=productname so on click of dropdown option i would like to append the value of that particular option into browser url something like this and redirect to that url http://www.browserurl.com/?search=productname&sort1desc=T&sort1=Item_ONLINECUSTOMERPRICE

I have tried this script

$(document).ready( function() {
$('#selectdropdown').bind('change', function () {
var brwsr_url=document.URL;
var redirecturl= brwsr_url + $(this).val();
location.href = redirecturl;
});

but the problem is when i select one option it append the value and page gets reload after reloading when i select other option it takes the whole url which has first option appended value something like this www.browserurl.com/search=productname&sort1desc=T&sort1=Item_ONLINECUSTOMERPRICE&sort1desc=F&sort1=Item_ONLINECUSTOMERPRICE

Upvotes: 0

Views: 1659

Answers (2)

Muhammad Bilal
Muhammad Bilal

Reputation: 2134

You can split the url on & like this:

$(document).ready( function() {
    $('#selectdropdown').bind('change', function () {
        var brwsr_url=document.URL;
        brwsr_url = brwsr_url.split('&');
        brwsr_url = brwsr_url[0]; 
        var redirecturl= brwsr_url + $(this).val();
        location.href = redirecturl;
   }); 
});

jsfiddle for your sample url: http://jsfiddle.net/cocxevyo/

Upvotes: 0

Sreelal P Mohan
Sreelal P Mohan

Reputation: 313

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

For more details, http://api.jquery.com/bind/

Upvotes: 0

Related Questions