Reputation: 26281
I would like to obtain the original selected value of a <select>
element as it was written by the initial HTML and defined by selected="selected"
. For instance, the original value of mySel is 2 no matter what the user selects. Or in other words, I would like to get the default value of the <select>
element similarly as I am doing with the below <input>
element. Thank you
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>Testing</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#click').click(function(){
console.log($("#myInput").val(),$("#myInput").attr('value'));
console.log($("#mySel").val(),$("#mySel").attr('value'),$('#mySel option:selected').val());
});
});
</script>
</head>
<body>
<button id="click">Click</button>
<input type="text" value="Default Value" id="myInput" name="myInput" class="valid">
<select id="mySel" name="mySel">
<option value="1">Value 1</option>
<option value="2" selected="selected">Value 2</option>
<option value="3">Value 3</option>
</select>
</body>
</html>
Upvotes: 1
Views: 1419
Reputation: 1575
Use to get select option of a select element like this:
$("#mySel option[selected]").val();
It will do the magic :)
Upvotes: -1
Reputation: 92903
Since this is specified as an attribute, you can select that:
$('#mySel option[selected]');
or even
$('#mySel [selected]');
This will select the original selected
value no matter what the user has changed it to.
http://jsfiddle.net/mblase75/szT4w/
Upvotes: 3