Reputation: 928
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
Reputation: 36703
jQuery
in your code.$(function(){ ... })
$('#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
Reputation: 167250
You need to use .text()
instead of .html()
:
$('#dropdown option:selected').text();
Or use .val()
$('#dropdown').val();
Upvotes: 0
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
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&
as it is parsed.
jQuery faithfully returns the fixed-up HTML when you ask it to.
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
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