简体   繁体   中英

JavaScript changing HTML code after loading in a div

I have a page that gets values from a DB, I can't control the values / how they are called, but the end result looks like standard HTML code, for example:

<div id="myDiv" class="controls">
    <select id="jform_province" name="jform[province]">
        <option value="AB">Alberta</option>
        <option value="BC">British Columbia</option>
        <option value="MB">Manitoba</option>
    </select>
</div>

I'm looking to put a script at the end of the page that can modify the option elements by say adding a function so it looks like this:

<option value="AB" onClick="someFunction()">Alberta</option>

How can I modify the code? I know how to edit the entire content of the div but I want to change the elements, I will not know what the values of the elements are so the script needs to find all option tags in "myDiv" (I have other lists on the page I don't want changed) and add that code to all of them.

Thanks

Just attach an event handler:

document.getElementById('jform_province').onchange = function() {
  switch(this.options[this.selectedIndex].value) {
    case "AB": someFunction(); break;
    // define other cases as needed
  }
};

Note that <option> elements do not fire onclick events when selected, and even if they did it wouldn't detect alternate input methods such as using the keyboard. The code above provides an alternative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM