Javascript - innerHTML not working with HTML select menus

后端 未结 8 1380
眼角桃花
眼角桃花 2020-11-30 15:18

In my HTML page I have 2 select menus with IDs \"month\" and \"day\" - \"day\" is empty when the page loads, \"month\" has 12 options with values 1-12 corresponding to Janua

相关标签:
8条回答
  • 2020-11-30 15:59

    I would suggest simply not to use innerHTML on a select - it just seems wrong. select elements have easy to use methods to add new options:

    `document.getElementById('day').options.add(new Option("1", "1"))`
    

    the parameters in the above object creation are:

    new Option("optionText", "optionValue")
    

    Just wanted to add to this answer, because it might clarify to someone who get to this post.

    0 讨论(0)
  • 2020-11-30 16:00

    I would generalize and summarize as follows the issue and the solution that worked for me:

    Problem:

    Javascript innerHTML not working on select HTML elements any more.

    Description:

    The standard Javascript syntax to dinamically assign HTML contents (document.getElementById().innerHTML=...) does not work any more on the select HTML elements since an unknown version of (probably all) either operating systems or most used browsers; using it on a select element causes the browser to crash.

    Solution:

    To dinamically assign HTML contents to an HTML select element, instead of using the standard syntax:

    document.getElementById(HTML_select_element_id).innerHTML = <HTML contents to assign>
    

    use this syntax:

    var select = document.getElementById(HTML_select_element_id);
    select.outerHTML = 
        select.outerHTML.replace(
            select.innerHTML
            ,
            <HTML contents to assign>
        )
    ;
    
    0 讨论(0)
提交回复
热议问题