简体   繁体   中英

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!

You can try:

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

DEMO

for once: In this line:

.find('option[value="'+ $('input[name=anzahl_eintraege]').val() +']')

You are missing the closing '"'. Should be:

.find('option[value="'+ $('input[name=anzahl_eintraege]').val() +'"]')

Next your .on() is executed while jQuery has your tag on top... I guess you want the change of the , not on the .

And you don't need to find the option tag yourself, jQuery can do that for you, using sortNo.val().

I believe that is what you want?: http://jsfiddle.net/KadrG/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM