jQuery adding several lines in html

Asked

Viewed 251 times

0

I’m using the following code:

 $("#divPrincipal").prepend('<p class="text-success">Você terá aproximadamente ' +     resultado + ' plantas </p>');

The idea was to click on a button and it will print the line with the result in my HTML form, however if the user keeps clicking on the button he will be replicating this line. Is there any way to overwrite the line, or write the line once, or print the result otherwise?

2 answers

2


Instead of complementing the content of the div with prepend (or append), define the whole content with .html():

$("#divPrincipal").html('<p class="text-success">Você terá aproximadamente ' + resultado + ' plantas </p>');

This clears the div and fills again with the past content.

  • Boy, am I dumb

  • Sometimes the solution is simpler than you think ;)

2

Just to complement the @bfavaretto response, if in any situation you have to put a result in a predetermined place, you can use the .text to change only the contents of an element:

var resultado = 17;
$("#resultado").text( 'Você terá aproximadamente ' + resultado + ' plantas');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="text-success" id="resultado"></p>

In this example, the <p> already exists in HTML, and you are only changing the content.

Note: different from .html, if you use a .text( 'um <em>dois</em> tres' ), the <em> will appear written literally instead of emphasizing the dois.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.