使用val()函数设置< select>的值时触发change()事件 [英] Trigger change() event when setting <select>'s value with val() function
问题描述
>我预计执行以下代码
$('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屋!