Reputation: 995
I am using the following function to print out the contents of javascript variables.
function message (){
$("#description").html("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%");
}
This correctly works as expected, however if i try this:
function message (){
$("#description").html("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%");
$("#description").html("Candidate " + (lowest2+1) + " was the second to get eliminated ending on " + results[lowest2][0]+ "%");
}
This obviously doesn't work. The second message overwrites the text of the first message. What is the proper way displaying both messages.
Upvotes: 1
Views: 2354
Reputation: 23943
You need to append, not replace the html of the display element.
So something like this:
$("#description").append("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%" + "<br />");
.append()
can take a jQuery object, native DOM element, or plain HTML string.
Depending on how structured your actual data are, a more robust approach would be to build a DOM fragment, then append that to the container:
function message (){
$('<div class="result">').html( _your_message_here_ ).appendTo('#description');
$('<div class="result">').html( _next_message_here_ ).appendTo('#description');
}
Then you can style div.result
as desired, not worry about line breaks, etc.
Upvotes: 0
Reputation: 123377
function message (){
var output;
output = "Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%";
output += "Candidate " + (lowest2+1) + " was the second to get eliminated ending on " + results[lowest2][0]+ "%";
$("#description").html(output);
}
keep DOM manipulation as few as possible for the sake of the performance (it will save you from unnecessary page repaints): just use a variable to contain all your strings and do the insertion once so to avoid multiple expensive calls to jQuery
function.
Upvotes: 4
Reputation: 1785
Use
$("#description").html("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%");
$("#description").append("Candidate " + (lowest2+1) + " was the second to get eliminated ending on " + results[lowest2][0]+ "%");
Upvotes: 1
Reputation: 171679
html()
method will replace all that is in selector.... I think you want append()
which adds to end of existing html
Upvotes: 0
Reputation: 29424
Use .append()
:
function message (){
$("#description").append("Candidate " + (lowest+1) + " was the first to get eliminated ending on " + results[lowest][0]+ "%");
$("#description").append("Candidate " + (lowest2+1) + " was the second to get eliminated ending on " + results[lowest2][0]+ "%");
}
Upvotes: 1