如何从 Javascript / jQuery 为选择框添加 onChange 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12496838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:32:04  来源:igfitidea点击:

How to add onChange attribute for select box from Javascript / jQuery

javascriptjqueryhtmljavascript-events

提问by Daya

I have select box with out onChange attribute. Now after loading the total page, based on some conditions i have to add 'onChange' for the select box from javascript. I am trying with the following code. But its not working.

我有没有 onChange 属性的选择框。现在在加载整个页面后,根据某些条件,我必须为来自 javascript 的选择框添加“onChange”。我正在尝试使用以下代码。但它不起作用。

$("#depositForm").attr(("onChange", "selectedMainDepositType('this');" ));

Its is not adding the onChange event.

它没有添加 onChange 事件。

<select id="depositForm_depositSubType" class="depositSubType" style="width:160px;" name="depositSubType"> 

has to be changed as

必须更改为

<select id="depositForm_depositSubType"  onchange="selectedMainDepositType(this);"  class="depositSubType" style="width:160px;" name="depositSubType">

Please suggest how to add the onChange attribute.

请建议如何添加 onChange 属性。

回答by JoeFletch

Did you try...

你试过了吗...

$("#depositForm").on("change", function(event) { 
     selectedMainDepositType(this);
} );

jQuery .on()

jQuery .on()

回答by John Conde

$("#depositForm").change(function(e){
    selectedMainDepositType($(this));
});

回答by Scorpio

 document.getElementById('depositForm').onchange = undefined;

 $("#depositForm").change(..);

Give it a shot.. I hope it works out for you.. Original post How to edit 'onchange' attribute in a 'select' tag? (using jquery)

试一试.. 我希望它对你有用.. 原帖如何编辑“选择”标签中的“onchange”属性?(使用jQuery)

回答by PIPetro

For anyone looking for another answer. I used this method because I had to first search for the dynamically created select list.

对于任何寻找另一个答案的人。我使用这种方法是因为我必须首先搜索动态创建的选择列表。

var dropdown = document.getElementsByTagName("select");
for (i=0; i<dropdown.length; i++) {
    if (dropdown[i].title == "Component") {
        dropdown[i].onchange = changeApproverCC;
    }
}