0

Im trying to get an option value and add it to the header location.

<select id="time">
<option value="1"> 1 hour</option>
<option value="2"> 2 hours</option>
</select>

When an option is selected from the above list it should then add it as a get variable to the current header url.. such as

header=www.test.com?time=2

<select id="time2">
<option value="1"> 1 min</option>
<option value="2"> 2 min</option>
</select>

While current header being www.test.com?time=2 If a value was chosen from that list then min=2 should be added to the current header. i.e - www.test.com?time=2&min=2

(there are multiple select options, so when each one is selected how can i add the get variable to the current header ?

$('time').on('change', function (e) 
{?
});

1 Answer 1

1

I'd suggest:

// binding an event-handler to the 'change' event (selecting by class-name):
$('.query').change(function(){
    // retrieving the current hash (though search is, of course, an alternative):
    var query = window.location.hash;
    /* if there is a current hash we apppend the name and value of the
       current select element to that hash:
    */
    window.location.hash = (query.length > 0 ? query + '&' : '') + this.name + this.value;
    // verifying the change/showing what was set/changed:
    console.log(window.location.hash);
/* triggering the change-handler function, this can be omitted if you don't
   want the handler to run on page-load: */
}).change();

Coupled with the slightly amended HTML:

<select name="hour" class="query">
    <option value="1"> 1 hour</option>
    <option value="2"> hours</option>
</select>

<select name="mins" class="query">
    <option value="1"> 1 min</option>
    <option value="2"> 2 min</option>
</select>

JS Fiddle demo.

This updates the window.location.hash (#time=2), rather than the window.location.search (?time=2) because updating the latter will cause the page to reload (with the new search-string), whereas updating the hash prevents the page from reloading.

If, however, the page-reload isn't a problem for you, then you can simply use the window.location.search instead of the window.location.hash.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi.. Thanks for your reply.. it works ! how ever though it keeps on adding time=2, time=1,time=1 .. when i reselect the option.. is there a way where i can change the get value for time if it already exists in the location hash instead of appending it to the existing one ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.