0

The below jQuery creates variables from XML data and places it in markup. The variable can be used between the <button> and </button> but when I try to use the variable for creating an argument for the value attribute (or anything else for that matter) I cannot. What is wrong with my syntax.

$.ajax({
  type: "GET",
  url: "Administration/data/people.xml"
  }).done(function (xml) {
  $(xml).find('fullName').each(function() {
    var fullName = $(this);
    $('<button></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
  });
}).fail(function (response, error) {
  $('#info').text('Error!!');
});

Dev Inspector shows:

<button value="[object] [Object]"><childnode>fullName</childnode></button>

But, instead, what I want is:

<button value="fullName">fullName</button>
Jim22150
  • 511
  • 2
  • 8
  • 22
  • 1
    The default string representation of an object is `[object Object]`, so that's what you see. JavaScript doesn't know how you want to represent the object as a string. You have to extract the information that you want from it. Simplified example: `var obj = {foo: 42}; alert(obj); alert(obj.foo);`. – Felix Kling Jan 24 '14 at 07:12

1 Answers1

2

Try to get the text inside fullname instead:

var fullName = $(this).text();

Currently, your $(this) point to fullName which is an object.

Felix
  • 37,892
  • 8
  • 43
  • 55
  • Felix thanks a ton! XML strings are certainly different than the serverside generated SQL data strings I am used to working with. I imagine the `.text()` method would also be needed to extract JSON too right? – Jim22150 Jan 24 '14 at 07:19
  • @Jim22150: This has nothing to do with JSON. `.text` is used to get the aggregated text content of a DOM element's descendants. JSON is parsed to JS objects and arrays and then you simply access them. Have a look at http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json if you are new to JavaScript objects. – Felix Kling Jan 24 '14 at 07:24
  • [text()](http://api.jquery.com/text/) method is only help you to get the text inside the tag. To extract JSON, it's pretty much depend on your JSON structure – Felix Jan 24 '14 at 07:25
  • @FelixKling Kling, great reference, but I was asking about rendering an external JSON file, but I guess you answered that anyway indirectly. Thanks again! – Jim22150 Jan 24 '14 at 08:13
  • @Jim22150: Yes, since it doesn't matter *where* the JSON comes from. Once parsed, you are dealing with JavaScript objects and arrays. Just like it doesn't matter where your XML comes from. Once it's parsed you are working with DOM elements. – Felix Kling Jan 24 '14 at 08:42