Solved

how do i assign an onchange function to a select field within my javascript code?

Posted on 2006-11-02
3
221 Views
Last Modified: 2008-02-07
i want to dynamically assign an onchange function to a select field in my javascript code.

so lets say i have this code:

function eventHandler(param1) {

           doSomeStuff(param1);
}

selectField.onchange=eventHandler("blah");



obviously this is the wrong way, what is the correct way?

selectField.onchange = function() { eventHandler("blah"); }


is this the correct way?





0
Comment
Question by:wrynn
3 Comments
 
LVL 6

Accepted Solution

by:
Basilisci earned 500 total points
ID: 17862501
This is ok:

selectField.onchange = function() { doSomeStuff("blah"); };

If you don't need to specify any parameters, you can also do

selectField.onchange=eventHandler;

or

selectField.onchange= doSomeStuff;


Another approach is to use addEventListener (allows to attach many listeners on the same event and element):

if (selectField.attachEvent) {
   selectField.attachEvent("onchange", function() { doSomeStuff("blah"); });  // this is for IE
} else {
   selectField.addEventListener("change", function() { doSomeStuff("blah"); }, false); // this for standards-compliant browser
}
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now