使用JavaScript获取选定的选项文本

时间:2013-02-20 09:35:41

标签: javascript html dom drop-down-menu

我有一个这样的下拉列表:

<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>

如何使用JavaScript获取实际选项文本而不是值?我可以通过以下方式获得价值:

<select id="box1" onChange="myNewFunction(this.selectedIndex);" >

但不是7122我想要cat

12 个答案:

答案 0 :(得分:130)

尝试选项

function myNewFunction(sel) {
  alert(sel.options[sel.selectedIndex].text);
}
<select id="box1" onChange="myNewFunction(this);">
  <option value="98">dog</option>
  <option value="7122">cat</option>
  <option value="142">bird</option>
</select>

答案 1 :(得分:52)

普通JavaScript

var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;

jQuery的:

$("#box1 option:selected").text();

答案 2 :(得分:6)

HTML:

<select id="box1" onChange="myNewFunction(this);">

JavaScript的:

function myNewFunction(element) {
    var text = element.options[element.selectedIndex].text;
    // ...
}

DEMO: http://jsfiddle.net/6dkun/1/

答案 3 :(得分:6)

所有这些功能和随机的东西,我认为最好使用它,并按照这样做:

this.options[this.selectedIndex].text

答案 4 :(得分:3)

据我所知,有两种解决方案。

这两个都只需要使用香草javascript

1 selectedOptions

现场演示

const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);

areaSelect.addEventListener(`change`, (e) => {
  // log(`e.target`, e.target);
  const select = e.target;
  const value = select.value;
  const desc = select.selectedOptions[0].text;
  log(`option desc`, desc);
});
<div class="select-box clearfix">
  <label for="area">Area</label>
  <select id="area">
    <option value="101">A1</option>
    <option value="102">B2</option>
    <option value="103">C3</option>
  </select>
</div>

2个选项

现场演示

const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);

areaSelect.addEventListener(`change`, (e) => {
  // log(`e.target`, e.target);
  const select = e.target;
  const value = select.value;
  const desc = select.options[select.selectedIndex].text;
  log(`option desc`, desc);
});
<div class="select-box clearfix">
  <label for="area">Area</label>
  <select id="area">
    <option value="101">A1</option>
    <option value="102">B2</option>
    <option value="103">C3</option>
  </select>
</div>


答案 5 :(得分:2)

使用 -

$.trim($("select").children("option:selected").text())   //cat

这是小提琴 - http://jsfiddle.net/eEGr3/

答案 6 :(得分:1)

你需要获取选项的innerHTML,而不是它的值。

<击>

使用this.innerHTML代替this.selectedIndex

编辑:您需要先获取选项元素,然后使用innerHTML。

使用this.text代替this.selectedIndex

答案 7 :(得分:1)

// split rows by \r\n.  Not sure if all csv has this, but mine did
const rows = rawCsvFile.split("\r\n");

// find all commas, or chunks of text in quotes.  If not in quotes, consider it a split point
const splitPointsRegex = /"(""|[^"])+?"|,/g;
const array2d = rows.map((row) => {
    let lastPoint = 0;
    const cols: string[] = [];
    let match: RegExpExecArray;
    while ((match = splitPointsRegex.exec(row)) !== null) {
        if (match[0] === ",") {
            cols.push(row.substring(lastPoint, match.index));
            lastPoint = match.index + 1;
        }
    }
    cols.push(row.slice(lastPoint));

    // remove leading commas, wrapping quotes, and unneeded \r
    return cols.map((datum) => 
        datum.replace(/^,?"?|"$/g, "")
        .replace(/""/g, `\"`)
        .replace(/\r/g, "")
    );
})

// assuming first row it props name, create an array of objects with prop names of the values given
const out = [];
const propsRow = array2d[0];
array2d.forEach((row, i) => {
    if (i === 0) { return; }
    const addMe: any = {};
    row.forEach((datum, j) => {
        let parsedData: any;
        if (isNaN(Number(datum)) === false) {
            parsedData = Number(datum);
        } else if (datum === "TRUE") {
            parsedData = true;
        } else if (datum === "FALSE") {
            parsedData = false;
        } else {
            parsedData = datum;
        }
        addMe[propsRow[j]] = parsedData;
    });
    out.push(addMe);
});

console.log(out);

但是:

 <select class="cS" onChange="fSel2(this.value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select><br>

 <select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
     <option value="0">S?lectionner</option>
     <option value="1">Un</option>
     <option value="2" selected>Deux</option>
     <option value="3">Trois</option>
 </select>

 <script type="text/javascript"> "use strict";
   const s=document.querySelector(".cS");

 // options[this.selectedIndex].value
 let fSel = (sIdx) => console.log(sIdx,
     s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);

 let fSel2= (sIdx) => { // this.value
     console.log(sIdx, s.options[sIdx].text,
         s.options[sIdx].textContent, s.options[sIdx].label);
 }

 // options[this.selectedIndex].text
 // options[this.selectedIndex].textContent
 // options[this.selectedIndex].label
 // options[this.selectedIndex].innerHTML
 let fSel3= (sIdx) => {
     console.log(sIdx);
 }
 </script> // fSel

还有这个:

 <script type="text/javascript"> "use strict";
    const x=document.querySelector(".cS"),
          o=x.options, i=x.selectedIndex;
    console.log(o[i].value,
                o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
 </script> // .cS"

答案 8 :(得分:0)

反应/最新JavaScript

onChange = { e => e.currentTarget.option[e.selectedIndex].text }

如果值在循环内,将为您提供确切的值。

答案 9 :(得分:0)

我只复制了所有amazon.com的“选择列表”,您可以从以下image.gif链接中查看演示。

see demo now

我喜欢amazon.com的“选择/选项” css样式和javascript技巧...

现在尝试。...

/***javascript code***/
  document.querySelector("#mySelect").addEventListener("click", () => {
    var x = document.querySelector("#mySelect").selectedIndex;
    let optionText = document.getElementsByTagName("option")[x].innerText;
    document.querySelector(".nav-search-label").innerText = optionText;
  });
/***style.css***/
  .nav-left {
    display: -webkit-box;
    display: -moz-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    position: static;
    float: none;
  }
  .nav-search-scope {
    display: -webkit-box;
    display: -moz-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    position: relative;
    float: none;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }
  .nav-search-facade {
    position: relative;
    float: left;
    cursor: default;
    overflow: hidden;
    top: 3px;
  }
  .nav-search-label {
    display: block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #555;
    font-size: 12px;
    line-height: 33px;
    margin-right: 21px;
    margin-left: 5px;
    min-width: 19px;
  }
  .nav-icon {
    position: absolute;
    top: 14px;
    right: 8px;
    border-style: solid;
    _border-style: dashed;
    border-width: 4px;
    border-color: transparent;
    border-top: 4px solid #666;
    border-bottom-width: 0;
    width: 0;
    height: 0;
    font-size: 0;
    line-height: 0;
  }
  .nav-search-dropdown {
    position: absolute;
    display: block;
    top: -1px;
    left: 0;
    height: 35px;
    width: auto;
    font-family: inherit;
    outline: 0;
    margin: 0;
    padding: 0;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
    visibility: visible;
    border: 0;
    line-height: 35px;
  }
<!--html code-->
<div class="nav-left">
  <div id="nav-search-dropdown-card">
    <div class="nav-search-scope nav-sprite">
      <div class="nav-search-facade">
        <span class="nav-search-label" style="width: auto">All</span>
        <i class="nav-icon"></i>
      </div>

      <select
        id="mySelect"
        class="nav-search-dropdown searchSelect"
        style="display: block; top: 3px"
        tabindex="0"
        title="Search in"
      >
        <option>All Departments</option>
        <option>Arts &amp; Crafts</option>
        <option>Automotive</option>
        <option>Baby</option>
        <option>Beauty &amp; Personal Care</option>
        <option>Books</option>
        <option>Computers</option>
        <option>Digital Music</option>
        <option>Electronics</option>
        <option>Kindle Store</option>
        <option>Prime Video</option>
        <option>Women's Fashion</option>
        <option>Men's Fashion</option>
        <option>Girls' Fashion</option>
        <option>Boys' Fashion</option>
        <option>Deals</option>
        <option>Health &amp; Household</option>
        <option>Home &amp; Kitchen</option>
        <option>Industrial &amp; Scientific</option>
        <option>Luggage</option>
        <option>Movies &amp; TV</option>
        <option>Music, CDs &amp; Vinyl</option>
        <option>Pet Supplies</option>
        <option>Software</option>
        <option>Sports &amp; Outdoors</option>
        <option>Tools &amp; Home Improvement</option>
        <option>Toys &amp; Games</option>
        <option>Video Games</option>
      </select>
    </div>
  </div>
</div>

答案 10 :(得分:0)

使用 Typescript 在 React 上获取它:

  const handleSelectChange: React.ChangeEventHandler<HTMLSelectElement> = (event) => {
    const {  options, selectedIndex } = event.target;
    const text = options[selectedIndex].text;
    // Do something...
  };

答案 11 :(得分:-1)

尝试以下方法:

myNewFunction = function(id, index) {
    var selection = document.getElementById(id);
    alert(selection.options[index].innerHTML);
};

请参阅here jsfiddle示例