# Type Delete ...">

Script mismatch table

I have a base table

html

<table id="damageList">
  <tr>
   <td>#</td>
   <td>Type</td>
   <td>Delete</td>
  </tr>
</table>

      

which i am trying to execute dynamically with

Js

function addDamage(){
  var trA= "<tr>";
  var trB= "</tr>";
  var td1= "<td>"+nmbr+"</td>";
  var td2= "<td>"+type+"</td>";
  var td3= "<td><a href='#confirmDialog'>X</a></td>";

  $("#damageList").append(trA, td1, td2, td3, trB);

  nmbr++;
}

      

(variable nmbr is line numbering and starts from 1, the type is decided dynamically elsewhere)

The problem is I am not getting a proper table.

What I am getting is this:

<table id="damageList">
  <tr>
   <td>#</td>
   <td>Type</td>
   <td>Delete</td>
  </tr>
  <tr></tr>
  <td>1</td>
  <td>K</td>
  <td>
   <a href="#confirmDialog">X</a>
  </td>
</table>

      

Can someone please tell me where I went wrong?

+3


source to share


2 answers


DOM doesn't work. You cannot add open / close tags separately. You must pass the full string representation of the element. What's happening:

$("#damageList")
     .append(trA, // append a TR, since `<tr>` can be parsed as an element
             td1, // append a TD
             td2, // append a TD
             td3, // append a TD
             trB // append a closing `</tr>` tag, silently fails
     ); 

      

You can concatenate strings and then feed them to jQuery.



$("#damageList").append(trA + td1 + td2 + td3 + trB);

      

Also note that you must wrap the strings with an element tbody

and add the generated strings to it:

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

      

+1


source


Try changing the function to the following:

function addDamage(){
  var val = [
     "<tr>",
     "<td>"+nmbr+"</td>",
     "<td>"+type+"</td>",
     "<td><a href='#confirmDialog'>X</a></td>",
     "</tr>"
  ].join('');

  $("#damageList").append(val);

  nmbr++;
}

      



jQuery will automatically parse your first unclosed one <tr>

and create it <tr></tr>

before adding it to #damageList

. Then he adds three <td>

to #damageList

. Finally, it discards the closure </tr>

since it doesn't know how to handle it. Combining the values ​​together before adding will solve your problem.

+2


source







All Articles