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>
1
  • 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);. Commented Jan 24, 2014 at 7:12

1 Answer 1

2

Try to get the text inside fullname instead:

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

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

Sign up to request clarification or add additional context in comments.

5 Comments

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: 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 stackoverflow.com/questions/11922383/… if you are new to JavaScript objects.
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
@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: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.