Pinkie
Pinkie

Reputation: 10256

jQuery select box make option selected based on url

I have a select box as follows. How do i mark an option as selected based on the last part of the url. ex: http://domain.com/index/one. The last part of the url is one so i want option one to be selected.

<select>
    <option id="one">One</option>
    <option id="two">Two</option>
    <option id="three">Three</option>
</select>

I'm looking for jQuery or Javascript Solution.

Upvotes: 1

Views: 2139

Answers (4)

Narendra Yadala
Narendra Yadala

Reputation: 9664

I think this should do, assuming URL has that last part you mentioned ('one' as in your question)

$('#selectid').val(window.location.href.substring(
                      window.location.href.lastIndexOf('/')+1))

Upvotes: 2

Smamatti
Smamatti

Reputation: 3931

I guess you are looking for: window.location Maybe parse a range from that url.

Sample: http://jsfiddle.net/R48GY/

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

var parts = window.location.href.split('/');
if (parts.length > 0) {
    $('#myselect').val(parts[parts.length - 1].split('?')[0]);
}

also make sure you fix your select and give values to your options, not ids:

<select id="myselect">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
</select>

Upvotes: 1

Steve Bergamini
Steve Bergamini

Reputation: 14600

Is there a reason why you're trying to do this with jquery/javascript? would seem more logical to do this with whatever server side language you're using. Maybe use a rewrite as well.

Upvotes: 0

Related Questions