lundi 26 juin 2017

JQuery: Cannot get elements from a table column

I am trying to dynamically some checkboxes buy using the values from a table column. While the table is created how it should (I fill it dynamically using a get request to my server), I can't get the values from any of its columns so I can use them. Here is my code:

$(document).ready(function() 
{
/*
$.get("sub3",function(responseJson) 
{
    if(responseJson!=null)
    {
        $("#table1").find("tr:gt(0)").remove();
        var table1 = $("#table1");
        $.each(responseJson, function(key,value) { 
            var rowNew = $("<tr><td></td><td></td><td></td><td></td></tr>");
            rowNew.children().eq(0).text(value['idp']); 
            rowNew.children().eq(1).text(value['producator']); 
            rowNew.children().eq(2).text(value['culoare']); 
            rowNew.children().eq(3).text(value['pret']); 
            rowNew.appendTo(table1); 
        }); 
    }
});
*/

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
       if (xmlhttp.status == 200) 
       {
            $("#table1").find("tr:gt(0)").remove();
            var table1 = $("#table1");
            var Data = JSON.parse(xmlhttp.responseText);
            $.each(Data, function(key,value) { 
                var rowNew = $("<tr><td></td><td></td><td></td><td></td></tr>");
                rowNew.children().eq(0).text(value['idp']); 
                rowNew.children().eq(1).text(value['producator']); 
                rowNew.children().eq(2).text(value['culoare']); 
                rowNew.children().eq(3).text(value['pret']); 
                rowNew.appendTo(table1); 
            });
       }
       else if (xmlhttp.status == 400) {
          alert('There was an error 400');
       }
       else {
           alert('something else other than 200 was returned');
       }
    }
};

xmlhttp.open("GET", "sub3", true);
xmlhttp.send();

createBox();
});


function createBox()
{
    var items=[];
    $('#table1 tr td:nth-child(2)').each( function()
    {
       items.push( $(this).text() );       
    });
    var items = $.unique( items );
    console.log(items);
    for (var i = 0; i < items.length; i++) 
    {
        addCheckbox(items[i]);
    }

}

function addCheckbox(name) 
{
   var container = $('#cblist');
   var inputs = container.find('input');
   var id = inputs.length+1;

   $('<input />', { type: 'checkbox', id: 'cb'+id, value: name 
}).appendTo(container);
   $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}

In the function createbox(), the console.log(items) prints [], when it should be filled with some values already added to my table. What am I doing wrong?




Aucun commentaire:

Enregistrer un commentaire