0

I have a drop-down menu, when I select any option, the page redirects. Now I want to make the page as the selected item in the drop down. Here is my code:

HTML:

<select class="MobileDropDown">
    <option value="/">Home</option>
    <option value="/technology">Topics</option>
    <option value="/about">About Us</option>
    <option value="/vendor">Vendor Directory</option>
    <option value="/popular-research">Popular White Papers</option>
</select>

Javascript:

<script type="text/javascript">
    $(".MobileDropDown").change(function(){
        window.location.href = $(this).val();
    });

    var URLMobile = window.location.href.split('/');

    $(".MobileDropDown option").each(function(){
        if($(this).val() == '/' + URLMobile[3]) {
            $(this).attr('selected', 'selected');
        }
    });
</script>

I am sure this is not the best way to do this, but how would I fix this?

4
  • What do you want, again? Commented Nov 25, 2013 at 18:01
  • 1
    You only need to apply a value to the select. The option should then be selected by default. E.g.: $('.MobileDropDown').val('/about');. Commented Nov 25, 2013 at 18:02
  • var addressValue = $(this).attr("href"); Gets the address of whatever was clicked. Commented Nov 25, 2013 at 18:02
  • Just do: $(".MobileDropDown").val("/" + URLMobile[3]); Commented Nov 25, 2013 at 18:04

2 Answers 2

1

Hope this helps..

$(document).ready(function(){
    $(".MobileDropDown").change(function(){
        window.location.href = $(this).val();
    });

    var URLMobile = window.location.href.split('/');

    $(".MobileDropDown").val("/" + URLMobile[3]);
})
Sign up to request clarification or add additional context in comments.

Comments

0

You can simplify the selecting process like this,

$(".MobileDropDown option:contains(" + '/' + URLMobile[3] + ")").prop('selected',true);

or

$(".MobileDropDown").val("/" + URLMobile[3]);

Comments

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.