Reputation: 6688
Having issues with dynamically creating <select>
tags and then populating them with XML values.
The jQuery appends a <div>
with a select and then adds <option>
tags from XML data.
My first XML / AJAX attempt. Done some extensive reading but keep coming up short.
Here's an example of my code:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script>
function addSelect() {
$("#myDiv").append(function(){
$.ajax({
type: "GET",
url: "test.xml"
dataType: "xml",
success: function(xml) {
$("#myDiv").append("<select id='mySelect'>");
$(this).find('value').each(function(){
var value = $(this).text();
$("#mySelect".append("<option class='ddindent' value='" + value + "'>" + value + "</option>");
});
$("#myDiv").append("</select>");
}
});
});
}
</script>
</head>
<body>
<div id="myDiv"></div>
<a href="#" onClick="addSelect();">Add Select</a>
</body>
</html>
Upvotes: 1
Views: 2855
Reputation: 39251
With your code, you're not reading the data from xml
. Change $(this)
to $(xml)
:
$(xml).find('value').each(function(){
var value = $(this).text();
$("#mySelect").append("<option class='ddindent' value='" + value + "'>" + value + "</option>");
});
Edit: Also changed mySelect
to #mySelect
as MMM pointed out, and fixed a syntax error (you hadn't closed the bracket around mySelect
.
Edit: You have a few other oddities in your code. I have fixed them below:
function addSelect() {
$.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function(xml) {
$("#myDiv").append("<select id='mySelect'>");
$(xml).find('value').each(function(){
var value = $(this).text();
$("#mySelect").append("<option class='ddindent' value='" + value + "'>" + value + "</option>");
});
$("#myDiv").append("</select>");
}
});
}
Upvotes: 1
Reputation: 7310
Change
$("mySelect".append("<option class='ddindent' value='" + value + "'>" + value + "</option>");
to
$("#mySelect").append("<option class='ddindent' value='" + value + "'>" + value + "</option>");
(added id selector)
Upvotes: 0