How to style table's content?

Viewed 108

I create table dynamically:

function createResultsTable(data) {
    var table = $('<table id="tblResultsList">');
    var tr;
    var td;

    $.each(data.d.foundItems, function(i, item) {

        var button = $('<button/>', {
            text: item.code, 
            click: function () { CellClicked(item.x,item.y,"") }
        }); 
        i % 3 === 0 && (tr = $('<tr>').appendTo(table));

        tr.append('<td>').prepend(button).end();
    });

    $('#rstSearch').append(table);
}

Here how it looks in the view now:

enter image description here

Here is the Fiddle.

Here is the desired look of the content:

enter image description here

Here is the Fiddle.

But I am stuck. I don't know how to move to the center content and make it quadratic.

4 Answers

That line is wrong:

tr.append('<td>').prepend(button).end();

What it actually does is append '<td>' and button to tr. That's because the return value of append is tr, not the new td tag. What you could do instead is:

$('<td>').append(button).appendTo(tr);

It will be better to read more about handlebars. In this files you can read real html and load it dynamically. This is the link. You can install hadlebars with npm install handlebars.

for arrange your content:

 var arr = [{"id":1,"name":"Mike"},{"id":2,"name":"Tom"},{"id":3,"name":"Herman"},{"id":4,"name":"Ursula"},{"id":5,"name":"Sam"},{"id":6,"name":"Jenny"},{"id":7,"name":"Helga"},{"id":8,"name":"Nikolas"},{"id":9,"name":"Surgen"},{"id":10,"name":"Jorg"}];

var table_str='<table id="tblResultsList" border="1"></table>';
$('#rstSearch').append(table_str);
var index=0;
var index_total=0;
var row_str='';
for(key in arr){
    index++;
    index_total++;
    if(index==1){
        row_str='<tr>';
    };
    row_str+='<td><input data-id="'+arr[key].id+'" class="my-btn" type="button" value="'+arr[key].name+'"></td>';
    if(index==4){
         row_str+='</tr>';
         index=0;
          $('#tblResultsList').append(row_str);
          row_str='';

     }
     if(arr.length==index_total){
          row_str+='</tr>';
          $('#tblResultsList').append(row_str);
     }
};
var btn_max_width = 0;
$('.my-btn').each(function(){
     var test_width=$(this).outerWidth(true);
     btn_max_width = Math.max(btn_max_width, test_width);
});
$('.my-btn').css({'width':btn_max_width, 'height':btn_max_width});


$('.my-btn').click(function(){
    var id=$(this).attr('data-id');
    alert(id);
});

like this:

Related