Sagarmichael
Sagarmichael

Reputation: 1624

jQuery object to string help please

I am creating a jquery object like so:

 htmlCode = $("<div id='"+data.layoutDescriptions[i].id+"'></div");

It seems to be missing some elements mainly when I am doing this:

if(data.type == "ListView"){

    htmlCode.append("<SELECT property='"+ data.property +"' size="+ data.listProps.length +" multiple>");
    i = 0;
    while(i < data.listProps.length){

        htmlCode.append("<OPTION value='"+ i+1 +"'>"+ data.listProps[i] +"</OPTION>");
        i++;
    }
    htmlCode.append("</SELECT>");

} 

where data is a Json object.

When i do this as a string it works. e.g. instead of

htmlCode.append("<OPTION value='"+ i+1 +"'>"+ data.listProps[i] +"</OPTION>");

i would do

htmlCode = htmlCode + "<OPTION value='"+ i+1 +"'>"+ data.listProps[i] +"</OPTION>";

I want to find out what is missing so I want to see the Object i have tried the following:

alert(JQuery.htmlCode.stringify());

alert(htmlCode.html);

Nether work.

Any Ideas??

Thanks.

Upvotes: 0

Views: 100

Answers (4)

codeling
codeling

Reputation: 11448

To get a string representation of DOM elements you can use what was posted in this other question.

However, using the methods provided in the other answers (console.log or Firebug) seem to be the easier choice because they work without code modifications.

Upvotes: 1

jjay225
jjay225

Reputation: 518

Try something like:

if(data.type == "ListView"){
   var options;
   htmlCode.append("<SELECT property='"+ data.property +"' size="+ data.listProps.length    +" multiple></SELECT>");
   i = 0;
   while(i < data.listProps.length){

       options+="<OPTION value='"+ i+1 +"'>"+ data.listProps[i] +"</OPTION>";
       i++;
   }
   $(htmlCode).find('select').html(options);

} 

Here is a demo Demo

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

Your first line of code

htmlCode = $("<div id='"+data.layoutDescriptions[i].id+"'></div");

declares the variable htmlCode as a jQuery object containing a single <div> element (defined by the HTML you passed to the function).

When you call

htmlCode.append("<SELECT property='"+ data.property +"' size="+ data.listProps.length +" multiple>");

you're appending a <select> element (again, defined by the HTML passed to the function) to the end of that <div> element, which works fine.

However, when you call

htmlCode.append("<OPTION value='"+ i+1 +"'>"+ data.listProps[i] +"</OPTION>");

you're also appending an <option> to the <div> element, not to the <select> element which is what you want.

It seems like you're trying to build a HTML string using a jQuery object and the .append() function, but that's not what jQuery does. jQuery works with actual elements, it just lets you pass HTML to create them.

Upvotes: 5

Asciiom
Asciiom

Reputation: 9975

You should use Firefox/Firebug to see you objects, browse through them, change them, ...

Upvotes: 0

Related Questions