3

REWRITE: I have a select field with an associated onchange event.

<select id='customer' onchange='loadRate(this.value)'>

At some point in my code, I assign a value to this select field with Javascript.

document.getElementById('customer').value = "Main St Packaging";

Why does this not trigger the onchange event? How do I fix it so that it does? Right now I am doing it by writing explicitly:

loadRate('Main St Packaging')

but I was wondering if there is a better way?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Daniel Kats
  • 5,141
  • 15
  • 65
  • 102
  • Can you not just make one function that updates all of the fields at once? – Matthew Riches Jun 03 '11 at 13:20
  • Well there are a lot of fields. That's basically what I did to get around this, but it seems pretty inefficient. – Daniel Kats Jun 03 '11 at 19:22
  • I'm not entirely sure if it's a duplicate, but the accepted answer seems relevant to your question: [Trigger onchange event manually](http://stackoverflow.com/questions/2856513/trigger-onchange-event-manually). – David Thomas Jun 06 '11 at 16:42

1 Answers1

2

Try calling the "onchange" method explicitly:

var el = document.getElementById('customer');
el.value = "Main St Packaging";
el.onchange(); // Will run "loadRate(this.value)", per your HTML.
maerics
  • 151,642
  • 46
  • 269
  • 291