views:

34

answers:

2

I have the following code which loads a xml file to populate a dropdown. I would like to put the selected options text into a variable. I already got the value of the selection but not the text.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"&gt;&lt;/script&gt;
<script>
$(document).ready(function(){
    $.ajax({
    type: "GET",
    url: "make10.xml",
    dataType: "xml",
    success: function(xml) {
    var select = $('#mySelect');

var optionsHtml = new Array();
$('make', xml).each(function(){
              var value = $(this).attr('value');
              var label = $(this).text();
optionsHtml.push( "<option class='ddindent' value='"+ value +"'>"+label+"</option>");

    });
    optionsHtml = optionsHtml.join('');
select.append(optionsHtml);

select.children(":first").text("Select Make").attr("selected",true);

} 
}); 

$('#mySelect').change(function() {
var val=$(this).val();
alert(val);
});


}); 
</script>
</head>
<body>
<div id="page-wrap">
<select id="mySelect">
<option>loading</option>
</select>
</div>
</body>
</html>
+1  A: 

var selectedOptionValue = $('#mySelect:selected').val();
var selectedOptionText = $('#mySelect:selected').html();

tuffkid
This won't return anything...the `<select>` itself isn't selected, it's the options that are selected :)
Nick Craver
+1  A: 

To get the text of the selected <option> you could use :selected and .text(), like this:

$("#mySelect :selected").text();

(Note the space, it's a child so it's important)

Or, inside your current .change() handler it would look like this:

$(this).children(":selected").text();
Nick Craver
Thanks again Nick!!! I had something like the second code but forgot the .children