Sunday, March 20, 2011

Javascript select drop down menu onchange not firing properly

my onchange isn't firing the javascript method properly.

Select code (in HTML file)

<select id="crit_1" onchange="crit1Update()">
    <option value=null>Criteria 1</option>
 <option value="major">Major</option>
 <option value="grad">Graduation Year</option>
</select>

crit1Update() code (in external filter.js file in same folder as HTML file containing the above with the following code in head of HTML

<script type="text/javascript" src="filter.js">
</script>

function crit1Update() {
 var crit1 = document.criteria.getElementsByID("crit1");
 var criteria1 = crit1.options[crit1.selectedIndex].value;
 alert("criteria1"); // this is never firing, so this isnt getting called
 if (criteria1 == null) {
  // eventually set all other lists to null in here as well
  filter(null,null,null,null,null,null)
            // the above returns all the resumes 
            // (this is eventually going to filter resumes)
 }
 else if (criteria1 == "major") {
  alert("Major!");
 }
}

Are there any glaring or not glaring errors that I am missing? I dont see why the alert("criteria1" isnt being called. I come from a java background and this is my first foray into JS, so I may be missing something simple.

Thanks for any help.

From stackoverflow
  • Your <select> ID is "crit_1" and your function is looking for ID "crit1" (no underscore).

    It would probably be a better idea to pass the <select> element as a reference to the function, eg

    JavaScript

    function crit1Update(crit1) {
        var criteria1 = crit1.options[crit1.selectedIndex].value;
    

    HTML

    <select id="crit1" name="crit1" onchange="crit1Update(this)">
    
    Ross Larson : thank you very much!
    klox : @Ross: read some tutorial for the project that do you want to built up. so it can prevent the mistake during type the script.
    Ross Larson : @Klox, that is probably a good idea. I have been going back and forth between my js doc, html doc and www.w3schools.com
    klox : yah w3schools is a place for beginner like me too.keep trying and learning.;)
  • There is a typo in this method call:

    document.criteria.getElementsByID(
    

    should be

    document.criteria.getElementById(
                                ^  ^ no "s" and lower case "d"
    

    also make sure the id matches your HTML element e.g. "crit_1"

    Phil Brown : Good catch on the first typo, but you also missed the "s" - `getElementsByID` should be `getElementById`
    Ross Larson : Thank you very much
    scunliffe : thanks @Phil Brown I was so focused on the "D" I missed the s.

0 comments:

Post a Comment