McNavy McNavy - 2 months ago 14
HTML Question

How to add row to table when enter key press using Jquery?

I have my table here (not full because he take around 200 lines). This code is use for create and fill one row :

<table>
<TR>
<TH>
<FORM>
<input name="designation" type="text" size="12" />
</FORM>
</TH>
<TH>
<SELECT size="1" id="ERDF" >
...
</SELECT>
</TH>
<TH>
<input name="famille" align="justify" type="text" size="12" />
</TH>
<TH>
<FORM>
<input name="conditionnement" align="justify" type="text" size="12" />
</FORM>
</TH>
<TH>
<!-- Tableau dynamique -->
<!-- APPELER LE CHAMP "total" -->
</TH>
<TH>
<div>
<input name="date_livraison" class="date_livraison" align="justify" type="date" size="12" />
</div>
</TH>
<TH>
<TABLE>
<TH>Nom
<input name="nom_recep" align="justify" type="name" size="12" />
</TH>
<TH>Portable
<input name="port_recep" align="justify" type="text" size="12" maxlength="10" />
</TH>
</TABLE>
</TH>
<TH>
<!-- Tableau fixe -->
<TABLE>
<TH>Meilleur prix
<FORM>
<input name="meilleur_prix" align="justify" type="text" size="12" />
</FORM>
</TH>
<TH>Fournisseur
<FORM>
<input name="fournisseur" align="justify" type="text" size="12" />
</FORM>
</TH>
</TABLE>
</TH>
</TR>
</table>


Then, I want add a row when user use the Entry key. For this, I use this (it's work) :

<script>
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
$("body").load("C:\wamp\www\plat_web\new_line.php")
}
// return false;
});
});
</script>


So, I want add the HTML code (first) when user use Entry key. I tested it but I have several tags and several were not detected because they are on a new line. How to correct this please?

Answer

You can use .append() to inserting new row to table.

$("tbody").append("<tr>...</tr>");

But if html of row is long and you want to copy it from document, you can use .clone() to copy html of row and use .appendTo() to appending copied html to end of table.

$("tbody > tr:first").clone().appendTo("table"); 

$(window).keydown(function(){
    if (event.keyCode == 13) {
        $("tbody > tr:first").clone().appendTo("table");       
        event.preventDefault();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>Col1</td>
        <td>Col2</td>
        <td>Col3</td>
        <td>Col4</td>
        <td>Col5</td>
    </tr>
</table>