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

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

问题描述

>我预计执行以下代码

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

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

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



嗯,情况并非如此。你需要通过这样做来实现triger change()事件

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

  $( '选择#一些')VAL(10).trigger( '变更'); 

但是,我正在寻找一些解决方案,一旦选择的值被更改,触发更改事件一些JavaScript代码。

解决方案

我有一个非常类似的问题,我不太确定你有什么问题,因为你建议的代码对我来说很棒。 立即(您的要求)触发以下更改代码。

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

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

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

如果数据库中的现有值为N,则立即隐藏辅助输入字段以我的形式。


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

I've expected that executing the following code

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

or

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

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

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

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

or

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

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();
}
});

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();

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天全站免登陆