franz1
franz1

Reputation: 351

How to use JQuery .append() method to add a string containing html?

I created a html page with a search form and I want to show a table with some data whenever the user clicks on the Search button.

I want to use JQuery to show such data instead than inserting a static html <tr>. I want to exploit the .append() method to add a string containing the <td> with data.

So I did the following:

I copypasted a bootstrap code for table and emptied the <tbody>, so the table won't show any row if results will not be returned.

I gave an ID to the <tbody>

This is the html code:

<table id="tabella" class="table hide">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Nome</th>
      <th scope="col">Cognome</th>
      <th scope="col">Indirizzo</th>
    </tr>
  </thead>
  <tbody id="tbody">
<!-- 

    <tr>
      <th scope="row">1</th>
      <td>Maria</td>
      <td>Ottone</td>
    </tr>


    <tr>
      <th scope="row">2</th>
      <td>Giacomo</td>
      <td>Troisi</td>
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Lorenza</td>
      <td>Pieri</td>
    </tr>

 <-->

  </tbody>
</table>

What I need to do now is appending the first <tr> of the table (previuìously deleted) to the <tbody> by using the JQuery .append() method, as if it were a string, by selecting the ID of the <tbody>.

function validateNome(){
  console.log('function validateNome has been activated');

  if ($("#inlineFormInputNome").val()=="") {
      $("#errorLog").show();    
  } else {          
    $("#errorLog").hide();    
    $("#cercaNome").prop("disabled", true);     
    setTimeout(function (){              
      $("#tabella").show();    

//What should I write inside the parentheses in the following line?

      $("#tbody").append("        ");

       $("#cercaNome").prop("disabled", false);    
    } , 2000);
  }
}

That's to say: is it possible to combine the append() method with the html() method in JQuery? Or: How may I use JQuery .append() method to add a string containing html code?

Upvotes: 0

Views: 62

Answers (1)

Louis Eloy
Louis Eloy

Reputation: 335

You can try something like this:

 $("#tabella tbody").append('<tr><th scope="row">2</th><td>Giacomo</td><td>Troisi</td>/tr>');

It will appened the <tr> after the last <tr> that's in the table.

Upvotes: 1

Related Questions