How can I add buttons at the end of each table row? - javascript

I'm trying to insert a button in the end of each row of the table receitas but the buttons are being set at the start of the table instead of the end of each row.
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for(let i in receitas) {
if(receitas[i].tipo==aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> '+ receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td></td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
The line where I put all the properties into the table row (inside of for), I have an input which should be set at the end of the row but instead, it is going to the top of the table.

It's just a type error in the cell wrapping the button you're creating </td> instead of starting <td>
see belown snippet :
receitas = [
{tipo:"typ1",nome:"nome1",tempo:"tempo1",custo:"custo1",dificuldade:"dificuldade1"},
{tipo:"typ2",nome:"nome2",tempo:"tempo2",custo:"custo2",dificuldade:"dificuldade2"},
{tipo:"typ1",nome:"nome3",tempo:"tempo3",custo:"custo3",dificuldade:"dificuldade3"},
{tipo:"typ1",nome:"nome4",tempo:"tempo4",custo:"custo4",dificuldade:"dificuldade4"},
]
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for (let i in receitas) {
if (receitas[i].tipo == aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> ' + receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td><td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
mostraTabelaTeste("typ1","table");
<div id="table"></div>

You may need to add one more th for button column in first row. Like below:
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th><th> </th></tr>';

Related

Dynamic Row addition to the Table

I want to add Array elements to the table.
Array elements are dynamic coming from the database. And i am creating the Row for adding the one row from the generated data and appending rowAfter to add the other array elements
Here is the code i have written -
var rowSpan = 0;
var rowSpan1 = 0;
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
var QuantityArray = data[element].quantity.split(',');
var ChemistArray = data[element].Retailername.split(',');
var PobArray = data[element].Pob.split(',');
rowSpan = productsArray.length;
rowSpan1 = ChemistArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
row += '<td>' + QuantityArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td><td>' + QuantityArray[i] + '</td>';
}
}
for (var k = 0; k < rowSpan1; k++) {
if(k == 0) {
row += '<td>' + ChemistArray[k] + '</td>';
row += '<td>' + PobArray[k] + '</td>';
} else {
rowAfter += '<td>' + ChemistArray[k] + '</td><td>' + PobArray[k] + '</td> </tr>';
}
}
row +=
'<td rowspan="'+rowSpan1+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan1+'">' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row+rowAfter);
So as per the code I can finely display ProductArray and Quantity Array
And But i am not able to display the Chemist array after one another.
In the above Image i want to display data( Kapila and Kripa below the Chemist column) Some where making issue with tr and td.
Any help would really appreciated.
Data is a JSON Response -
In my case, ChemistArray(Retailername in response) contains 4 names and POBArray 4 values.
You need to add an empty <td></td> as a "placeholder".
for (element in data) {
var productsArray = data[element].products.split(',');
var quantityArray = data[element].quantity.split(',');
var chemistArray = data[element].Retailername.split(',');
var pobArray = data[element].Pob.split(',');
// find the largest row number
var maxRows = Math.max(productsArray.length, quantityArray.length, chemistArray.length, pobArray.length);
var content = '';
var date = '<td rowspan="' + maxRows + '">' + data[element].date + '</td>';
var doctorName = '<td rowspan="' + maxRows + '">' + data[element].doctor_name + '</td>';
var locations = '<td rowspan="' + maxRows + '">' + data[element].locations + '</td>';
var area = '<td rowspan="' + maxRows + '">' + data[element].area + '</td>';
content += '<tr>' + date + doctorName;
for (var row = 0; row < maxRows; row++) {
// only add '<tr>' if row !== 0
// It's because for the first row, we already have an open <tr> tag
// from the line "content += '<tr>' + date + doctorName;"
if (row !== 0) {
content += '<tr>';
}
// the ternary operator is used to check whether there is items in the array
// if yes, insert the value between the <td></td> tag
// if not, just add an empty <td></td> to the content as a placeholder
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>';
content += '<td>' + (quantityArray[row] ? quantityArray[row] : '') + '</td>';
content += '<td>' + (chemistArray[row] ? chemistArray[row] : '') + '</td>';
content += '<td>' + (pobArray[row] ? pobArray[row] : '') + '</td>';
// only add "locations + area + '</tr>'" if it is the first row
// because locations and area will span the whole column
if (row === 0) {
content += locations + area + '</tr>';
} else {
content += '</tr>';
}
}
$('#tbody').append(content);
}
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>'; is just a short-hand for
content += '<td>';
if (productsArray[row]) {
content += productsArray[row];
} else {
content += '';
}
content += '</td>';
If there is item in the productsArray[row], let's say productsArray[0], which is 'Sinarest', then productsArray[row] would be truthy. Else, if there is no more products in the array, such as productsArray[3] will gives us undefined, which is a falsy value and the corresponding conditional will be ran.

Ajax Data Display fetched from Database

I have a data coming from the database. And Displaying when the ajax function is called. I am able to display it. But, One of the variable is an array data and saved it using implode function. Data is like (a,b,c,d).
Data is displaying in the below format
data1 Data2 Data3 (a,b,c,d) Data5 and so on.
I want to explode the array data and print one below the another.
I should display it like
data1 data2 data3 a data5
b
c
d
Here is the code which i am written to get the data.
<script type="text/javascript">
$('#genreport').on('click',function(){
var Representativeid = document.getElementById("Representativeid").value;
var dateFrom = document.getElementById("dateFrom").value;
var dateTo = document.getElementById("dateTo").value;
var url = '{{URL::to('/admin/GenReport')}}';
$.ajax({
type : 'get',
url : url,
data : {Representativeid:Representativeid,dateFrom:dateFrom,dateTo:dateTo},
success:function(data){
console.log(data);
var $tabledata = $('#tbody');
$tabledata.empty();
for (element in data)
{
var row = '<tr>' +
'<td>' + data[element].date + '</td>'+
'<td>' + data[element].doctor_name + '</td>'+
'<td>' #foreach(explode(',', data[element].products ) as $product)
{{$product}}
#endforeach '</td>' +
'<td>' + data[element].quantity + '</td>'+
'<td>' + data[element].locations +'</td>'+
'<td>' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row);
}
},
error:function(data)
{
alert('fail');
alert(data);
}
});
});
</script>
I am failing in the for-each logic. Please help me to display as i expected.
You cannot use a php function/code(server-side) in your javascript/jQuery code(client-side), as the php code will be parsed before the page is loaded. Instead you need to use javascript code.
First, you need to split the value into an array
var productsArray = data[element].products.split(',');
then you would need to get the array count (.length) to use a rowspan, so it doesn't break your table stucture
var rowSpan = productsArray.length;
....
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
....
finally, you need to loop in javascript, not php, through the array. (note, because the i<0 <td>s go on subsequent rows, you need to add them after)
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
so it would look something like this -
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
// get products array count
var rowSpan = productsArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
row +=
'<td rowspan="'+rowSpan+'">' + data[element].quantity + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].area + '</td>'+
'</tr>';
// append both row and the <td>s in rowAfter
$('#tbody').append(row+rowAfter);
}
just add <tr><td> inside foreach.
Edit:
Also, take a look at this link. table inside a td

Deleting selected Item from Panel -JS

Below is my code which works this way. when user selects checkbox, it appends the selected item name and price and calculates the sub total based on the quantity the user types in.
Now when a user deselects a checkbox, the item deselected disappears and the total reduces the total to the old total (previous total).
What I want to achieve is, my html below I can icon fa fa-close which I want it to perform like how when a checkbox is deselected. So when a user clicks on the icon, it removes the respective item and also reduces the total to the old total
function order(food) {
var ad = JSON.parse(food.dataset.food),
existing;
if (food.checked == true) {
$('.panel').append(
'<div class="container" style=" font-size:14px; "> ' +
'<input type="hidden" value=' + ad.id + ' data-id="' + ad.id + '" name="food_id[]" />' +
'<table style="width:100%;" class="table" id="tables">' +
'<thead>' +
'<thead>' +
'<tbody id="item_list">' +
'<tr>' +
'<td class="icon" ><i class="fa fa-close"></i></td>' +
'<td class="name" >' + ad.name + '</td>' +
'<td class="price" data-price="' + ad.price + '">' + ad.price + '</td>' +
'<td><p class="total" ><span class="line-total" name="total" id="total"></span></p></td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'</div>'
)
}
} else {
var total = $(".panel .container [data-id=" + ad.id + "]").parent().find(".total").text();
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
if (total) {
$('.checkout span').text(function(index, oldtext) {
console.log('this is my old text ' + oldtext)
return oldtext ? oldtext - total : oldtext;
});
}
}
$('.panel').on('keyup', '.quantity', function() {
order_container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
points = Number($(this).closest('div').find('.points').data('points'));
order_container.find(".total span").text(quantity * price);
order_container.find(".pts-total span").text(quantity * points);
sum = 0;
points = 0;
$(".line-total").each(function() {
sum = sum + Number($(this).text());
})
$(".pts-total").each(function() {
points = points + Number($(this).text());
})
$('.checkout span').text(sum);
});
You can try this simple click event
$('.panel').on('click','.fa.fa-close',function(){
$(this).closest('.container').remove();//remove the current element
var sum = 0;
$(".line-total").each(function(){
sum = sum + Number($(this).text());
});//calculate the new sum
$('.checkout span').text(sum);
})

how do i append in this function?

i have this code:
for (var i = 0; i < data.times.length; ++i) {
var time = formatTime(data.times[i].time);
tableContent += '<tr><td>' + data.times[i].destination.name + '</td><td id="appendLate' + i + '">' + time + '</td><td>' + data.times[i].track + '</td><td>' + data.times[i].train_type + '</td><td>' + data.times[i].company + '</td></tr>'
// laat vertragingen zien (BETA)
if (data.times[i].delay / 60 >= 1) {
$('#appendLate' + i + '').append("+" + data.times[i].delay / 60).addClass("late");
}
}
table.html(tableContent);
}
The if statement appends stuff and adds a class. i know it wont work like this.. but i cant seem to get how it WIL work.. Can some one help?
See it live: http://codepen.io/shiva112/pen/JGXoVJ?editors=001
Well, you're basically almost there. The right way to do it is to build the entire string before doing any DOM manipulation, since DOM operations are very slow (relatively).
Let's say your index.html looks like:
<html>
<head>
<title>Cool site!</title>
</head>
<body>
<table id="myCoolTable"></table>
</body>
</html>
Then your JavaScript simply becomes:
var tableContent = '';
for (var i = 0; i < data.times.length; ++i) {
var time = formatTime(data.times[i].time);
tableContent += '<tr>'
+ '<td>' + data.times[i].destination.name + '</td>';
if (data.times[i].delay / 60 >= 1) {
tableContent += '<td id=\'appendLate\'' + i + ' class=\'late\'>' + time + '</td>' + '+' + (data.times[i].delay / 60);
} else {
tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>';
}
tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>'
+ '<td>' + data.times[i].track + '</td>'
+ '<td>' + data.times[i].train_type + '</td>'
+ '<td>' + data.times[i].company + '</td>'
+ '</tr>';
}
$('#myCoolTable').html(tableContent);
What this does is build the HTML for the entire table. Then update the table only once. Hope it helps!

Pulling Form Variables through Javascript in a For Loop

I have a webpage that based on user input populates with form fields, as done by the following:
function Go2() {
var loans = document.getElementById('count').value;
var content = document.getElementById('stage3').innerHTML;
content = '<TABLE Width="100%">'
+'<TR>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Name</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Number</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Origination Date</TD>'
+'</TR>'
+'</TABLE>';
document.getElementById('stage3').innerHTML = content;
for(var i=0; i<loans; i++) {
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE Width="100%">'
+ '<TR>'
+ '<TD Width="30%"><INPUT Name="CName'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="CNumber'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="Date'
+ i
+ '" Size="40" Type="text"></TD>'
+ '</TR>'
+ '</TABLE>';
}
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE><TR><TD><INPUT Type="Button" Value="Submit" onClick="Go3()"></TD></TR></TABLE>';
}
Now what I need to do is iterate through the form and pull out the values for each of the form fields. This is about as far as I've gotten:
for (var n=0; n<loans; n++) {
content += '<TR>'
+ '<TD Colspan="2">'
+ document.getElementById('CName + n').value
+ '</TD>'
+ '<TD Colspan="2">'
+ document.getElementById('CNumber + n').value
+ '</TD>'
+ '<TD>'
+ document.getElementById('Date + n').value
+ '</TD>'
+ '</TR>';
}
Which does...Nothing. The last notable progress I had was getting it to spit out "null" which isn't really progress at all. I've looked at eval, but there's quite a few warnings against it.
Any Ideas?
I think you want
document.getElementById('CName' + n).value
(where n is outside of the quotes)
Well it should be 'CName' + n - i.e., you got the quotation marks in the wrong place
If all your controls are in a form, then you can access them as:
var allControls = document.<formId>.elements;
or
var allControls = document.forms[formId].elements;
Then iterate over the list of controls to get the values. The form controls must have names to be successful, no need for IDs. You can also get the values as:
var value = allControls['CName' + n].value;
or just
var form = docment.forms[formID];
var value = form['CName' + n].value;

Categories

Resources