Search code examples
javascriptjqueryeventshtml-select

how to set the selected option of a select element without triggering a change event?


I'm currently using this on a select:

var sortNo = $('select[name=anzahl_eintraegeSEL]');

sortNo
    // set selected based on hidden input default value
    .find('option[value="'+ $('input[name=anzahl_eintraege]').val() +']')
    .attr('selected', 'selected').attr('set',true)
    // set up change listener
    .on('change', function(){
        // do sth
        });

I want to set the default option to selected without triggering an initial change event.

How can I get this to work? The above seems to trigger a change event right away.

Thanks for help!


Solution

  • You can try:

    sortNo.on('change', function(){
        // do sth
    }).val($('input[name=anzahl_eintraege]').val()); // set default value from hidden field
    

    DEMO