Why does the jquery change event not trigger when I set the value of a select using val()?

后端 未结 9 785
猫巷女王i
猫巷女王i 2020-11-22 09:34

The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse

相关标签:
9条回答
  • 2020-11-22 10:22

    If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:

    window.setTimeout(function() { jQuery('.languagedisplay').change();}, 1);
    
    0 讨论(0)
  • 2020-11-22 10:25

    Adding this piece of code after the val() seems to work:

    $(":input#single").trigger('change');
    
    0 讨论(0)
  • 2020-11-22 10:35

    I believe you can manually trigger the change event with trigger():

    $("#single").val("Single2").trigger('change');
    

    Though why it doesn't fire automatically, I have no idea.

    0 讨论(0)
提交回复
热议问题