使用 val() 函数设置 <select> 的值时触发 change() 事件 [英] Trigger change() event when setting &lt;select&gt;&#39;s value with val() function

查看:64
本文介绍了使用 val() 函数设置 <select> 的值时触发 change() 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设置select元素的值时触发change事件的最简单和最好的方法是什么.

What is the easiest and best way to trigger change event when setting the value of select element.

我期望执行以下代码

$('select#some').val(10);

$('select#some').attr('value',  10);

将导致触发更改事件,我认为这是非常合乎逻辑的事情.对吗?

would result in triggering the change event, which i think is pretty logic thing to be done. Right?

好吧,事实并非如此.您需要通过执行此操作来触发 change() 事件

Well, it isn't the case. You need to triger change() event by doing this

$('select#some').val(10).change();

$('select#some').val(10).trigger('change');

但我正在寻找一些解决方案,一旦某些 javascript 代码更改了 select 的值,就会触发更改事件.

but i'm looking for some solution which would trigger change event as soon as select's value is changed by some javascript code.

推荐答案

我遇到了一个非常相似的问题,我不太确定您遇到了什么问题,因为您建议的代码对我来说效果很好.它立即(您的要求)触发以下更改代码.

I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.

$('#selectField').change(function(){
    if($('#selectField').val() == 'N'){
        $('#secondaryInput').hide();
    } else {
        $('#secondaryInput').show();
}
});

然后我从数据库中获取值(这在表单上用于新输入和编辑现有记录),将其设置为选定值,并添加我缺少的部分以触发上述代码,".change()".

Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".

$('#selectField').val(valueFromDatabase).change();

这样,如果数据库中的现有值为N",它会立即隐藏表单中的辅助输入字段.

So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.

这篇关于使用 val() 函数设置 <select> 的值时触发 change() 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆