Accessing events without using event attributes on html elements

Say you have a <select> and you want something to happen when it changes. Normally you would use the onChange event like,

<select id="myselect" name="myselect" onChange="myfunc()">
<option>opt1</option><option>opt2</option>
</select>

So when someone changes the select value, the myfunc() function will be fired.

You can also do this another way without tying an even to it directly. Here's how.

<select id="myselect" name="myselect" onChange="myfunc()">
<option>opt1</option><option>opt2</option>
</select>
<script type="text/javascript">
var sel = document.getElementById('myselect');
sel.onchange = function()
{
     myfunc();
}
</script>

GOTCHAS

  • Make sure your javascript is inserted below the field you are acting on, or that it's in the onLoad event, otherwise your actions might not happen because the page hasn't loaded yet.
  • Another VERY important thing to look at is the capitalization or lack there of on that part that looks like sel.onchange. Notice the previous example use onChange. The lowercase version on sel.onchange must be that way. It must be lowercase ONLY!!!. When tying to html elements, there are not capitalization requirements. You could use onChange, OnChange, onCHANGE or anything else.

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.