adding an onchange event to select

13,371

Solution 1

selectBox.onchange = showLines; should solve your problem.

in some browsers onchange get fired only after blurring select box. to over come this you can use onclick instead of onchange

Solution 2

My guess is that you're doing this:

selectBox.onchange = showLines();

If that's the case, just remove the ():

selectBox.onchange = showLines;
Share:
13,371

Related videos on Youtube

Admin
Author by

Admin

Updated on September 15, 2022

Comments

  • Admin
    Admin over 1 year

    I have the following js code:

    function createConBox() {
       var charDiv = document.getElementById("characterList");  // reference to "characterList" div
       header = document.createElement("p");  // creates the <p> tag
       charDiv.appendChild(header);  // adds the <p> tag to the parent node
       title = document.createTextNode("Show Only Lines By:");  // creates the text string
       header.appendChild(title); // adds the text string to the parent node
    
       // create select box and add elements
       selectBox = document.createElement("select");   
       selectBox.setAttribute("id", "cList");
       charDiv.appendChild(selectBox);
    
       charNames = uniqueElemText("h3");   // array of character names
       newOption = document.createElement("option");
       selectBox.appendChild(newOption);
       newOptionTitle = document.createTextNode("Show All Lines");
       newOption.appendChild(newOptionTitle);
       for (i = 0; i < charNames.length; i++) {
          newOption = document.createElement("option");
          selectBox.appendChild(newOption);
          newOptionTitle = document.createTextNode(charNames[i]);
          newOption.appendChild(newOptionTitle);
       }
    
    }
    
    function showLines() {
       alert("The Box has been changed");
    }
    

    Every time the option in the box is changed, I want it to call 'showLines()'. However, every time I try to implement an event, I can only get it to trigger when the page loads, and never again thereafter. Any help would be greatly appreciated.