javascriptjquerygoogle-chrome-extensionchained

jquery.chained.min.js set value of 2nd select


In my google chrome extension options.html, I use a chained select to get a value which I store in chrome.storage, which works great.

Now when I reopen my options.html I want to get the values out of my chrome.storage and set the chained select again to those values. My code works for setting the first select, but the 2nd one stays empty. How can I set both select to the chrome.storage values?

Here is a fiddle example of my problem: http://jsfiddle.net/timw1984/2hxzem1e/2/

As you can see the first select changes on button click but the 2nd one doesn't.

options.html:

<select id="choose-channel" name="accounts">
    <option value="MLB">MLB</option>
    <option value="NFL">NFL</option>
    <option value="2">NBA</option>
</select>
<select id="choose-channel-2" name="searches">

<option class="MLB" value="Orioles">Orioles</option>
<option class="MLB" value="RedSox">Red Sox</option>
<option class="MLB" value="Yankees">Yankees</option>
<option class="NFL" value="49ers">49ers</option>
<option class="NFL" value="Bears">Bears</option>
<option class="NFL" value="Bengals">Bengals</option>
</select>

options.js:

    var team, sport ;
$("select").addClass("ui-selectmenu-button ui-widget ui-state-default ui-corner-all");
$("#choose-channel-2").chained("#choose-channel");

chrome.storage.sync.get({
        sport1:"MLB",
        favoriteTeam: 'RedSox'
    }, function(items) {
        document.getElementById('choose-channel').value = items.sport1;
        document.getElementById('choose-channel-2').value = items.favoriteTeam;

    });
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
    save_options);

Thanks!

Tim


Solution

  • Just setting the value through .val()/.value often does not trigger the same kind of processing as interacting with the input element does.

    You should trigger an event that indicates that the value has changed:

    $('#choose-channel').val(items.sport1).change(); // or .trigger("change")
    $('#choose-channel-2').val(items.favoriteTeam).change();
    

    Your JSFiddle, patched.