2010-03-03 6 views
0

J'ai un code html précédent.Ajouter dynamiquement des lignes à une table html avec

<table width="600px" cellspacing="0" border="1" id="mainTable"> 
      <tr> 
       <th> 
        Name 
       </th> 
       <th> 
        full Name 
       </th> 
       <th> 
        Type 
       </th> 
      </tr> 
      <tr> 
       <td> 
        <input id="11" type="text" /> 
       </td> 
       <td> 
        <input id="12" type="text" /> 
       </td> 
       <td> 

        <select id="13"> 
        </select> 
       </td> 
      </tr> 
     </table> 
     <input type="button" onclick="return btnAddRow_onclick()"/> 

Je veux une fonction jquery qui va ajouter une ligne avec des éléments html et avec un nouvel identifiant. par exemple, après avoir cliqué, ajoutera:

<tr> 
       <td> 
        <input id="21" type="text" /> 
       </td> 
       <td> 
        <input id="22" type="text" /> 
       </td> 
       <td> 

        <select id="22"> 
        </select> 
       </td> 
      </tr> 
+3

Vos identifiants ne sont pas valides. id ne peut pas commencer par un numérique. – rahul

+1

pouvez-vous ajouter une ligne "modèle", avec id = "modèle" définissant l'affichage à aucun. Lorsque vous voulez une nouvelle ligne, il suffit de copier/cloner et de définir l'identifiant si nécessaire. – scunliffe

+0

Je sais, c'est seulement une démo. pour une compréhension rapide de mon problème. vous pouvez le lire comme 'txt11', txt12 '; 'chb13' – loviji

Répondre

1

Quelque chose comme

<script> 
    $(function(){ 
     var currentID = 1; 

     $("#btn1").click(function(){ 
      currentID ++; 
      var htmlToAppend = "<tr><td><input id='txt" + currentID + "1' type='text' /></td><input id='txt" + currentID + "2' type='text' /></td><td><select id='cmb" + currentID + "3'></select></td></tr>"; 
      $("#mainTable").append (htmlToAppend); 

     }); 
}); 
</script> 
<table width="600px" cellspacing="0" border="1" id="mainTable"> 
      <tr> 
       <th> 
        Name 
       </th> 
       <th> 
        full Name 
       </th> 
       <th> 
        Type 
       </th> 
      </tr> 
      <tr> 
       <td> 
        <input id="txt11" type="text" /> 
       </td> 
       <td> 
        <input id="txt12" type="text" /> 
       </td> 
       <td> 

        <select id="cmb13"> 
        </select> 
       </td> 
      </tr> 
     </table> 
     <input type="button" id="btn1" value="Click me" /> 
Questions connexes