jQuery 选择框的 Onchange 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13154274/
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-26 12:20:25  来源:igfitidea点击:

Onchange Event of Select Box

jqueryhtml

提问by Ashish Mehta

I am using an onchange event of select boxwith jquery. On change I have given display property = nonein other div. Problem is that when I got data from database and set it in select box so onchangeproperty is not applied for given value. Why? My code

我正在使用onchange event of select box带有 jquery 的。关于我display property = none在其他 div 中给出的更改。问题是,当我从数据库中获取数据并将其设置在选择框中时,因此onchange不会对给定值应用属性。为什么?我的代码

<select id="patientType" name="Patient_Type">
<option value="">--SELECT--</option>
<option value="OPD">OPD</option>
<option value="IPD">IPD</option>
</select>
<div id="roomInfo" clasas="inactive"></div>

Script

脚本

$('#patientType').change(function() {
 if ($('#patientType').val() == 'IPD') {
  if ($('#roomInfo').hasClass('inactive')) {
   $('#roomInfo').removeClass('inactive');// CSS Property Display None in this class
   $('#roomInfo').addClass('active');
  }
 } else {
  if ($('#roomInfo').hasClass('active')) {
     $('#roomInfo').removeClass('active');
     $('#roomInfo').addClass('inactive');
    }
 }
});

now i got data From database and set it this select patientType $('#patientType').val(data fetch From the database); can not apply onchange event apply and not display my roomInfo div so it is possible or not . or another method for getting that method. Please help. Thanks In Advance.

现在我从数据库中获取数据并将其设置为 selectpatientType $('#patientType').val(data fetch From the database); 不能应用 onchange 事件应用并且不显示我的 roomInfo div,所以可能与否。或获取该方法的另一种方法。请帮忙。提前致谢。

回答by Ashwin Preetham Lobo

Since you changing the value manually. You need to trigger the .change() event of select box. Refer the following link.

由于您手动更改了值。您需要触发选择框的 .change() 事件。请参考以下链接。

http://api.jquery.com/change/

http://api.jquery.com/change/

or else

要不然

if you loading the data through ajax use like following

如果您通过 ajax 加载数据,请使用如下所示

$('#patientType').on("change",function() {
   //Your code here
});

回答by PanditCR

Set an change event in jQuery:

在 jQuery 中设置更改事件:

$("#ddl").change(function(){
    alert($(this).val());
});

回答by Ashish Mehta

Get Value of Select Box and set it like this:

获取选择框的值并设置如下:

$("#patientType option[value='`OPD']").attr("selected","selected");