Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected option text with JavaScript

People also ask

How do I get the text value of a selected option JavaScript?

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

How do you get the text value of a selected option?

Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected"). text(); alert ($var);


Try options

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>

Plain JavaScript

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

jQuery:

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

All these functions and random things, I think it is best to use this, and do it like this:

this.options[this.selectedIndex].text

There are two solutions, as far as I know.

both that just need using vanilla javascript

1 selectedOptions

live demo

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 options

live demo

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>


HTML:

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

JavaScript:

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

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