user1269625
user1269625

Reputation: 3209

jQuery dropdown menu selected

I have this dropdown menu and on change, the window.location.href changes, but how would i go about making the selected value selected when the page changes?

<div class="iPhoneNav">
    <select class="iPhoneDropdown">
            <option value="/">Home</option>
            <option value="/services">Services</option>
            <option value="/about-us">About Us</option>
            <option value="/gallery">Gallery</option>
            <option value="/testimonials">Testimonials</option>
            <option value="/tours">Tours</option>
            <option value="/contact-us">Contact Us</option>
            <option></option>
    </select>
    <script type="text/javascript">
            (function($){

                    $(function(){
                            $('select').change(function(index){
                                    window.location.href = $(this).val();
                            });

                    });

            })(jQuery);     
    </script>

Upvotes: 0

Views: 854

Answers (2)

Snehal S
Snehal S

Reputation: 875

You can store some value or id of the selected option in body or with some elements with "data ". Give unique ids to your option tags.After selecting option store the selected option "id" with data.

Try this,

<div class="iPhoneNav">
<select class="iPhoneDropdown">
        <option id="1" value="/">Home</option>
        <option id="2" value="/services">Services</option>
        <option id="3" value="/about-us">About Us</option>
        <option id="4" value="/gallery">Gallery</option>
        <option id="5" value="/testimonials">Testimonials</option>
        <option id="6" value="/tours">Tours</option>
        <option id="7" value="/contact-us">Contact Us</option>
        <option></option>
</select>
<script type="text/javascript">
        (function($){

                $(function(){

                        if($('body').data('selected_opt') != "" || $('body').data('selected') != 'undefined') {
                            var op_id = $('body').data('selected_opt');
                            $('select').find('option[id="' + op_id + '"]').attr('selected', true);    //you can also use prop instead of attr
                        }
                        $('select').change(function(index){
                            $('body').data('selected_opt', $(this).attr('id'));
                            window.location.href = $(this).val();
                        });

                });

        })(jQuery);     
</script>

Upvotes: 0

helion3
helion3

Reputation: 37481

If you're using select like this example, just try to set the value using the pathname:

$(function(){
    $('.iPhoneDropdown').val(location.pathname);
});

Upvotes: 2

Related Questions