Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2006-11-02
3
Medium Priority
?
231 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 2000 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
This article discusses how to create an extensible mechanism for linked drop downs.
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…
Suggested Courses

885 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