Reputation: 3418
I have 4 blocks of xml, that I want to parse whith jQuery making one ajax call. Now four blocks of xml are different from each other(But the structure is same). I am trying to parse this xml by passing an id to each of the xml block, But in my ajax call I am not able to retreive the id attribute as it is the first thing that I need to capture to pass to the ajax function.
I tried something like this:
XML is here:
<dropdown>
<test id="1">
<optionheading>
<heads>Heading 1</heads>
<value>
<values images='images/1.gif'>Option1</values>
<values images='images/2.gif'>Option2</values>
<values images='images/3.gif'>Option3</values>
</value>
</optionheading>
.....................................
............................
</test>
<test id='2">
<optionheading>
<heads id="b">H..................
..................
............
</test>
</dropdown>
I need to get id of test1, test2, et-al
Ajax is Here:
$("document").ready(function() {
$.ajax({
type: "GET",
url:"dropdown.xml",
dataType: "xml",
success :function(xml) {
var select = $("#mySelect");
//I am getting id here
var id=$(xml).find('test').attr('id');
$(xml).find('test'+id).each(function() {
$(this).find('optionheading').each(function() {
var opthead = $(this).fin......................
Upvotes: 0
Views: 1731
Reputation: 348992
If I've understood you well, the following should happen (output boldfaced):
<test id="IDHERE">
should populate <select ID="IDHERE">
<optionheading>
should create an <optgroup>
with a label as defined at <heads>
<optgroup>
is populated with <option>
elements, according to the given <values>
elementsThe code below is the jQuery method to implement this idea, as requested.
Note: $('test', xml)
is a shorthand for $(xml).find('test')
.
Note2: Since an ID must be unique, select#yourID
is equal to #yourID
.
Note3: The <values>
tag at the XML is not necessary for this script.
success: function(xml){
//Loop through each `<test>`
$('test', xml).each(function(test_index){
var id = $(this).attr('id'); //Get the ID of the `<test>`
// Select <select> element with ID `ID` using the `select#ID` selector
var select = $('select#' + id);
$('optionheading', this).each(function() {
$('values', this).each(function(){
var $values = $(this);
$('<option>')
.val($values.attr('images'))
.text($values.text())
.appendTo(optgroup);
});
$('<optgroup>')
.attr('label', $('heads', this).text())
.appendTo(select);
});
});
}
Possible HTML after executing:
<select id='1'>
<optgroup label='Heading 1'>
<option value='images/1.gif'>Option1</option>
<option value='images/2.gif'>Option2</option>
<option value='images/3.gif'>Option3</option>
<optgroup>
....
</select>
<select id="2">
...
Upvotes: 1