Skip to content Skip to sidebar Skip to footer

Update Options In Select Dynamically

I have constructed a dynamic select using jQuery like below: Based on YesOrNo, I have to show/hide options in Source and Type Yes/No Source Type ------------

Solution 1:

You can call $("...").change() after the page is loaded:

$(function(){
    $('#YesOrNo').change();
});

See my fiddle:

I also hid the options when nothing is selected, calling $("...").hide() in the "onchange" event handler.

The $(func) with func as an anonymous function is a syntatic suggar for $(document).ready(func), which calls that given function after loading.

The "change" call is just a trigger call, like $("...").trigger("change").

Solution 2:

You can use trigger to manually invoke the handler on page load.... still your solution will not work in IE... see further changes below

var sourceHtml = $('#Source').html();
var typeHtml = $('#Type').html();
$('#YesOrNo').on('change', function () {
    var sources = $(sourceHtml);
    var types = $(typeHtml);
    var aob = $(this).find('option:selected').data('aob');

    if(aob){
        sources = sources.filter('[data-aob="' + aob + '"]');
        types = types.filter('[data-aob="' + aob + '"]');
    }
    $('#Source').empty().append(sources)
    $('#Type').empty().append(types)
}).triggerHandler('change');

Demo: Fiddle

Solution 3:

You can simply do this by triggeringchange event on load.

just add below code inside document.ready

$('#YesOrNo').trigger('change');

and for test it add selected="selected" for No option and run the code.

See Demo

Solution 4:

If your code logic allows this trigger a change event once.

//Triggering a change event on document ready
$(document).ready(function(){    
    $('#YesOrNo').trigger('change');
});

JS FIDDLE

Post a Comment for "Update Options In Select Dynamically"