heybit heybit - 1 month ago 14
HTML Question

JavaScript, Adding html to jQuery append function

I am trying to use jQuery to add buttons on a page. I would like the buttons to appear vertical instead of horizontal. So I try

$(".guess").append("<p>" + guess_answer + "</p>");


But then it prints to the page:

[object Object]

[object Object]

[object Object]

[object Object]

Instead of the buttons. I have test the code without the paragraph tags and it works but doesn't when the html is place in it.

var question1 = {
question: "What is 4 times 1?",
answer: "Dream On",
possible: [1,2,3,4],
boolean: [true,false,false,false]
};


function generate () {
$(".question").html(question1.question);

for (var i = 0; i < question1.possible.length; i++) {
var guess_answer = $('<button>');
guess_answer.addClass("options text-center btn-group-lg");
guess_answer.attr({
"data-boolean" : question1.boolean[i]
});

guess_answer.text(question1.possible[i]);
//guess_answer.append(question1.possible[i]);

$(".guess").append("<p>" + guess_answer + "</p>");
}
}

Answer

Use guess_answer.prop("outerHTML") to get the element as HTML string

var question1 = {
    question: "What is 4 times 1?",
    answer: "Dream On",
    possible: [1,2,3,4],
    boolean: [true,false,false,false]
};


function generate () {
    $(".question").html(question1.question);

    for (var i = 0; i < question1.possible.length; i++) {       
        var guess_answer = $('<button>');
        guess_answer.addClass("options text-center btn-group-lg");
        guess_answer.attr({
            "data-boolean" : question1.boolean[i]
        });

        guess_answer.text(question1.possible[i]);
        //guess_answer.append(question1.possible[i]);

        $(".guess").append("<p>" + guess_answer.prop("outerHTML") + "</p>");
    }
}
Comments