sierra.charli3
sierra.charli3

Reputation: 225

jQuery Use URL hash to select option forms

I'm trying to use URL hash to select option and when the option changes, url hash changes. I got two scripts, they work independently, but not together. Is there a solution? currently it works with url.com/#Apple, which selects Apple. But when I change selection to Orange, the URL doesn't change to url.com/#Orange Fiddle http://jsfiddle.net/q33zevup/1/

<select id="myselect">
    <option>Apple</option>
    <option>Orange B</option>
    <option>Pineapple</option>
    <option>Banana</option>
</select>

 <script>
    $('#myselect').change(function(){
        var url = $(this).val();
        window.location.hash = url;
    });
    </script> 
    <script>
    jQuery.noConflict();
    window.addEventListener('hashchange', fn, false);

    window.onload = fn; // fire on pageload

    function fn() {
        document.getElementById('myselect').value = window.location.hash.replace('#','');
    }
    </script>

Upvotes: 1

Views: 1368

Answers (1)

Gregg Duncan
Gregg Duncan

Reputation: 2725

It works for me after changing the "myselect" in the javascript to match the "mySelect" (case difference) in the html. http://jsfiddle.net/q33zevup/3/

$(function(){
    $('#mySelect').change(function () {
        var url = $(this).val();
        window.location.hash = url;
        console.log('select Changed');
    });
});
window.addEventListener('hashchange', fn, false);

window.onload = fn; // fire on pageload

function fn() {
    $('#mySelect').val(window.location.hash.replace('#', ''));
    console.log("hash = " + window.location.hash);
}

Upvotes: 2

Related Questions