Reputation: 2055
<select id="MyId" name="Myname">
<option value=1>Tom</option>
<option value=12>Harold</option>e
<option value=32>Jenny</option>
</select>
With
$('select option:selected').each(function () {
var $el = $(this);
var text = $el.attr('text');
alert(text);
});
I can get Options text
But how to get Select tag name or id and selected option text? As following return undefined:text
$('select option:selected').each(function () {
var $el = $(this);
var text = $el.attr('text');
var name = $el.attr('name');
alert(name + ":" + text);
});
Upvotes: 0
Views: 57
Reputation: 136
You can try this. Its works for me.
<!doctype html>
<html lang="en">
<head>
<title>Select Box</title>
<script data-main="js/main" src="lib/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('select[name="choice"]').change(function () {
var mySelect = $(this);
alert("selected " + mySelect.find('option:selected').text());
});
});
</script>
</head>
<body>
<select name="choice" >
<option value='1'>Choice 1</option>
<option value='2'>Choice 2</option>
<option value='3'>Choice 3</option>
<option value='4'>Choice 4</option>
<option value='5'>Choice 5</option>
</select>
</body>
</html>
Upvotes: 0
Reputation: 148150
Use closest()
or parent()
to get the select whose id and name is required.
$('select option:selected').each(function () {
var select = $(this).parent('select');//the tag object
alert($(this).closest('select').attr('id'));//id
alert($(this).parent('select').attr('name'));//name
});
Upvotes: 1
Reputation: 15393
Use .change()
$('select').change(function() {
var name = $(this).attr('name'); // get select tag name
var id = $(this).attr('id'); // get select tag id
var selectedOption = $(this).val(); // get selected option
var selectedText = $(this).find('option:selected').text(); // get selected option text
});
Upvotes: 4
Reputation: 185
Try This
$('select option:selected').each(function () {
var $el = $(this);
var text = $el.text();
alert(text);
});
Upvotes: 1