DJTronix DJTronix - 3 months ago 13
HTML Question

Populate Select Box from XML using jQuery

I've seen several examples here on how to do this and have successfully implemented others that use attributes. This time I'm given XML without attributes and i'm trying to figure out how to populate my select list from the node values instead of attributes. I keep getting objects returned instead of text. What am I doing wrong here?

code:


var code_data;
$.get('Book.xml', function (data) {
code_data = data;
var that = $('#BookDropdown');
$('Book', code_data).each(function () {
$('<option />', {
text: $('BookName').val('label'),
value: $('BookID').val('value')
}).appendTo(that);
});
}, 'xml');


XML:

<BookList>
<Book>
<BookName>Book One</BookName>
<BookID>1</BookID>
</Book>
<Book>
<BookName>Book Two</BookName>
<BookID>2</BookID>
</Book>
<Book>
<BookName>Book Three</BookName>
<BookID>3</BookID>
</Book>
<Book>
<BookName>Book Four</BookName>
<BookID>4</BookID>
</Book>
<Book>
<BookName>Book Five</BookName>
<BookID>5</BookID>
</Book>
</BookList>



Answer

The way you are accessing BookName and BookID is wrong. . .use following code instead. `

var code_data;
  $.get('Book.xml', function(data) {
    code_data = data;
    var that = $('#BookDropdown');
    $('Book', code_data).each(function() {
      $('<option />', {
        text: $('BookName',this).text(),
        value: $('BookID',this).text()
      }).appendTo(that);
    });
  }, 'xml');

`

Comments