简体   繁体   中英

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>

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');

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM