Get inner html of the selected option

前端 未结 5 1333
深忆病人
深忆病人 2020-12-15 21:30

I have something like this:

select = document.getElementById(\"select\");
select.onchange = function(){
  alert(this.value); //returns the selected value
  a         


        
相关标签:
5条回答
  • 2020-12-15 22:14

    This will work.

    select = document.getElementById("select");
    select.onchange = function(){
        alert(this.value); //returns the selected value
        alert(this.innerHTML); //returns the entire select with all the options
        var options = this.getElementsByTagName("option");
        var optionHTML = options[this.selectedIndex].innerHTML;  
        alert(optionHTML); //this is what I want, but it works now
    };
    
    0 讨论(0)
  • 2020-12-15 22:18

    Try:

    alert(this.options[this.selectedIndex].text);
    

    Demo:

    <select onchange="alert(this.options[this.selectedIndex].text)">
      <option>foo
      <option>bar
      <option>foobar
    </select>

    0 讨论(0)
  • 2020-12-15 22:24

    After doing some research it appears as though the browser (Chrome anyway) will strip out tags from option values making it impossible to get the actual HTML code. For example, given the following HTML:

    <html>
      <body>
        <select>
          <option><b>test 1</b></option>
          <option><b>test 2</b></option>
        </select>
      </body>
    </html>
    
    • document.getElementsByTagName('select')[0].options[0].text returns 'test 1'
    • document.getElementsByTagName('select')[0].options[0].innerHTML returns 'test 1'
    • document.getElementsByTagName('select')[0].options[0].firstChild returns a text node containing 'test 1'
    • document.getElementsByTagName('select')[0].firstChild.nextSibling returns the first option node. Its first child is the text node 'test 1'
    0 讨论(0)
  • 2020-12-15 22:32

    I haven't tested it, but this might work:

    alert(this.options[this.selectedIndex].innerHTML)
    
    0 讨论(0)
  • 2020-12-15 22:34

    I would recommend using this snippet:

    alert(this.selectedOptions[0].text)
    

    Demo:

    <select onchange="alert(this.selectedOptions[0].text)">
      <option value="1">one</option>
      <option value="2">two</option>
      <option value="3">three</option>
    </select>

    The selectedOptions is an HTML collection which contains all selected options. Using this snippet gives more advantage than this.options[this.selectedIndex] when you are using multi-select. In the case of a multi-select dropdown, this.selectedOptions will contain all selected elements. You can iterate through this collection to get innerHTML of all selected items.

    0 讨论(0)
提交回复
热议问题