10

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:

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

Its is not adding the onChange event.

<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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Daya
  • 724
  • 3
  • 14
  • 32
  • There's almost never a good reason to use any of the `[on*]` attributes, so don't bother. – zzzzBov Sep 19 '12 at 14:30
  • don't think about event as you do with attributes ... in-line events are parsed at document loading and it is not meant to be edited like a classic attribute afterward – Stphane Sep 19 '12 at 14:33

5 Answers5

22

Did you try...

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

jQuery .on()

JoeFletch
  • 3,820
  • 1
  • 27
  • 36
  • If you need to remove the handler, use `$("#depositForm").off("change");`. Is the attr `onChange` attached when the page is generated? – JoeFletch Sep 19 '12 at 14:48
6
$("#depositForm").change(function(e){
    selectedMainDepositType($(this));
});
John Conde
  • 217,595
  • 99
  • 455
  • 496
0
 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)

Community
  • 1
  • 1
Scorpio
  • 1,151
  • 1
  • 19
  • 37
0

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;
    }
}
PIPetro
  • 1
  • 4
0

You could try this:

document.getElementById("depositForm").addEventListener('change', (event) => {
 selectedMainDepositType('this');
});

Hope can help you :)

paas
  • 11
  • 1