natilas12 natilas12 - 2 months ago 11
Javascript Question

Add new row after specified number of columns added javascript

I've been working in getting a dashboard with buttons, each button will represent one machine. This buttons are generated depending on the Jquery results.

Currently, I would like to have 10 buttons added in one row, and then to continue adding them in a new row. Also, my other issue is that I want to change the button color depending on the result of the ajax.

I've tried the following code, but it is giving me as a result the image that I've attached below.

IMAGE: http://i68.tinypic.com/296oysw.png

(Sorry, couldn't post the image since I'm new to Stackoverflow)

$( document ).ready(function(){
var d = new Date();
var now = d.getTime() + 300;
var color;
var u = '/read/machines/' +{{userid}};
$.ajax({
url: u,
type: "GET",
dataType: 'json',
success: function(data) {
$.each(data, function(i, item) {
if (item.lastCommunication > now ){
color = "success";
}else{
color = "warning";
}
if (i != 0 && i%10 == 0){
$('<tr>').append(
$('<td>').append(
$('<button type="info" id="info" class="btn btn-'+color +' btn-lg" ontouchstart="touchAvailable=true; machineInfo('+item.id +');" onclick="if(!touchAvailable) machineInfo('+item.id +');">'+item.name+'</button>')
)
).appendTo('#body');
}else{
$('<td>').append(
$('<button type="info" id="info" class="btn btn-'+color +' btn-lg" ontouchstart="touchAvailable=true; machineInfo('+item.id +');" onclick="if(!touchAvailable) machineInfo('+item.id +');">'+item.name+'</button>')
).appendTo('#body');
}
});
}
});
});
</script>

Answer

I think the td element in the else branch show be append to #body tr:last

if(i%10 == 0){
 $('<tr>').appendTo('#body');
}

$('<td>').append(BUTTON_CODE).appendTo('#body tr:last');