Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the display value of Select using javascript

Tags:

javascript

<Select>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</Select>

I am using document.getElementById("Example").value; to get the value.

I want to display the text instead of the value. eg. value=1 --> One. How can I get the One text?

like image 892
alkhader Avatar asked Apr 11 '12 06:04

alkhader


2 Answers

In plain JavaScript you can do this:

const show = () => {
  const sel = document.getElementById("Example"); // or this if only called onchange
  let value = sel.options[sel.selectedIndex].value; // or just sel.value
  let text = sel.options[sel.selectedIndex].text;
  console.log(value, text);
}

window.addEventListener("load", () => { // on load 
  document.getElementById("Example").addEventListener("change",show); // show on change
  show(); // show onload
});
<select id="Example">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

jQuery:

$(function() { // on load
  var $sel = $("#Example");
  $sel.on("change",function() {
    var value = $(this).val();
    var text = $("option:selected", this).text();
    console.log(value,text)
  }).trigger("change"); // initial call
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Example">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
like image 126
mplungjan Avatar answered Oct 18 '22 03:10

mplungjan


Here the selected text and value is getting using jquery when page load

$(document).ready(function () {
var ddlText = $("#ddlChar option:selected").text();
var ddlValue = $("#ddlChar option:selected").val();
});

refer this

http://csharpektroncmssql.blogspot.in/2012/03/jquery-how-to-select-dropdown-selected.html

http://praveenbattula.blogspot.in/2009/08/jquery-how-to-set-value-in-drop-down-as.html

like image 20
Bhaskarreddy Mule Avatar answered Oct 18 '22 02:10

Bhaskarreddy Mule