Create table in JQuery HTML

1

I have a question, I have a function in JavaScript to generate tables, in the following way:

 function AgregarTabla(idContenedor, idTabla) {

            var htmlTabla;
            htmlTabla=
                    "<table id = '" + idTabla + "'>\n\
                <thead>\n\
                    <tr bgcolor='FFFDC1'>\n\
                        <th>Columna 1</th>\n\
                        <th>Column 2</th>\n\
                        <th>Columna 3</th>\n\
                    </tr>\n\
                </thead>\n\
            </table>";

            $("#" + idContenedor).append(GenerarTabla);

        }

As you can see, it is written in text / html format, but I would like to know if there is any way to write the same but in JQuery format. I understand that something like this should be done:

       var jQueryTabla = $("<table></table>");
       jQueryTabla.attr({
       id:idTabla});

       $("#" + idContenedor).append(GenerarTabla);

But then I do not know how to add the tr and th.

Thank you in advance. Greetings.

    
asked by Carlos Daniel Zárate Ramírez 26.06.2018 в 04:08
source

2 answers

1

I'm not sure I understand your question, but if all you want is to insert elements into your table using jQuery you can use the append()

method

var jQueryTabla = $("<table></table>");
       jQueryTabla.attr({
       id:"idtabla"});
       
function addRow(){
  var nuevoTr = "<tr bgcolor='FFFDC1'><th>Columna 1</th><th>Column 2</th><th>Columna 3</th></tr>";
  jQueryTabla.append(  nuevoTr );
}
$("#contenedor").append(jQueryTabla);
$("#addRow").click(function(){
	addRow();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contenedor">
</div>
<button id="addRow">
  Agregar fila
</button>
    
answered by 26.06.2018 в 07:05
1

I guess you want to add dynamism to the table, one way is with a loop and in each iteration you add a new th. As follows:

"use strict";
function generarTabla(){
    let $tr = $("<tr></tr>");
    //$tr.attr("bgcolor", "FFFDC1");
    $tr.css("background-color", "#FFFDC1");
    let $th;
    let i = 0;
    while (i++ < 3){
        $th = $('<th>columna ${i}</th>');
        $tr.append($th);
    }
    return $tr;
}
function agregarTabla(id_contenedor, id_tabla){
    const $tabla = $("<table></table>");
    $tabla.attr("id", id_tabla);
    $tabla.append(generarTabla());
    $("#" + id_contenedor).html($tabla);
}
$('document').ready(() => {
    $("#btn-agregar-tabla").click(() => agregarTabla("contenedor", "id-tabla"));
})
    <div id="contenedor"></div>
    <input type="button" value="Agregar tabla" id="btn-agregar-tabla">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I hope I have been of help.

    
answered by 26.06.2018 в 09:04