V.J.
V.J.

Reputation: 928

How to get selected option value of dropdown using jquery?

I am using dropdown and I want to get value of selected option.

I am able to do that using jquery html() method.

But in case selected option value is containing html encodable character lets say it is &(ampersand.)

alert('html() : ' + $('#dropdown option:selected').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="dropdown">
<option selected>Test & Get knowledge</option>
</select>

Then this & is encoded to &a m p;

How to treat this value as only text?

Upvotes: 0

Views: 6391

Answers (5)

void
void

Reputation: 36703

  1. Include jQuery in your code.
  2. Wrap your code in DOM Ready $(function(){ ... })
  3. Use $('#dropdown option:selected').val() to fetch the value.

$(function(){
alert('html() : ' + $('#dropdown option:selected').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
<option selected>Test & Get knowledge</option>
</select>

& will be parsed as & only and will not be changed.

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

You need to use .text() instead of .html():

$('#dropdown option:selected').text();

Or use .val()

$('#dropdown').val();

Upvotes: 0

V.J.
V.J.

Reputation: 928

https://jsfiddle.net/programtheweba/8gohx47g/

By using Jquery text(), we will get only text and characters are not encoded.

alert('text() : ' +$('#dropdown').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="dropdown">
<option selected>Test & Get knowledge</option>
</select>

Upvotes: 3

Milind Anantwar
Milind Anantwar

Reputation: 82241

& is a special character in HTML (it's used for entities) and cannot appear as a normal character.
Your HTML is invalid (&x is not an entity), but the browser automatically corrects it to &amp; as it is parsed.
jQuery faithfully returns the fixed-up HTML when you ask it to.

Source

Hence use .text() instead of .html():

$('#dropdown option:selected').text();

You can also use .val() along with select element selector to get selected options text value:

 $('#dropdown').val();

Upvotes: 1

Alex Char
Alex Char

Reputation: 33228

You can use jquery .text() instead:

console.log('text() : ' + $('#dropdown option:selected').text());//prints out text() : Test & Get knowledge
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
  <option selected>Test & Get knowledge</option>
</select>

Upvotes: 0

Related Questions