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.
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))
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>
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.
I guess you are looking for: window.location
Maybe parse a range from that url.
Sample: http://jsfiddle.net/R48GY/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.