Row being inserted above table when using jquery - javascript

I am trying to populate a table using jquery on my website. When I write the HTML manually on the HTML page it works, but when I replace it with a div and use jquery to append html to it, it inserts the HTML just above the table headers.
It is pulling information that the user created on a table on a different tab to ask the user to confirm the input before submitting.
The row I manually enter (Adult, 4.99, 0,) all appear as they should, but the rows appended to div ticketconfirmation appear above the table. The Jquery is called once the user presses continue on the page where they originally entered the data.
Can anyone explain why this is happening?
Thanks
HTML
<table class="table table-hover">
<thead>
<tr>
<th>Ticket Name</th>
<th>Ticket Price</th>
<th>Max Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adult/td>
<td>4.99</td>
<td>0</td>
</tr>
<div id="ticketconfirmation"></div>
</tbody>
JQuery
function getNodes() {
console.log("Getting node info");
$("#ticketconfirmation").text('');
var table = $('#sample_editable_1').DataTable();
var data = table.rows().data();
for (var i = 0; i < data.length; i++) {
$("#ticketconfirmation").append('<tr>');
var row = table.row(i).data();
$("#ticketconfirmation").append(
"<td>" + row[0] + " </td><td> " + row[1] + " </td><td> "
+ row[2] + "</td></tr>");
}
};

remove your <div id="ticketconfirmation"></div>
and try this one:
var newRow;
for (var i = 0; i < data.length; i++) {
var row = table.row(i).data();
newRow = "<tr><td>" + row[0] + " </td><td> " + row[1] + " </td><td> "
+ row[2] + "</td></tr>";
$('table.table tbody').append(newRow);
}

for (var i = 0; i < data.length; i++) {
var tableRow = $('<tr></tr>');
var row = table.row(i).data();
tableRow.append("<td>" + row[0] + " </td><td> " + row[1] + " </td><td> " + row[2] + "</td>");
$("#ticketconfirmation").append(tableRow);
}
You can give the id ticketconfirmation on tbody and remove that div.

Related

Load table via list ajax

I'm trying to load a table via post ajax, but it's not loading properly.
table:
<table class="table table-responsive table-hover table-striped" id="tableestoque" style="font-size:12px;">
<thead>
<tr>
<th>Nome Empresa</th>
<th>Qtd</th>
</tr>
</thead>
<tbody></tbody>
</table>
And here is how I am loading:
$.each(data.listaEstoque, function (i, item) {
$("#tableestoque").append("<tr"
+ "<td>" + item.empresaProduto.nome + "</td>"
+ "<td>" + item.qtd + "</td>"
+ "</tr>")
});
It is loading like this, I want you to load each one into a column, and if you have more rows, each in a row.
I created sample fiddle for you. Right now you are iterating over each element, not over each object. You should iterate over object using forEach statement.
var data = [{
id: 1,
name: 'Name1'
}, {
id: 2,
name: 'Name2'
}];
var $table = $("#tableestoque");
var $tr, $td1, $td2;
data.forEach(function(item) {
$tr = $('<tr>');
$td1 = $('<td>' + item.id + '</td>');
$td2 = $('<td>' + item.name + '</td>');
$tr.append($td1).append($td2);
$table.append($tr);
});
It looks like you need to append your html to <tbody> like this:
$.each(data.listaEstoque, function (i, item) {
$("#tableestoque tbody").append("<tr"
+ "<td>" + item.empresaProduto.nome + "</td>"
+ "<td>" + item.qtd + "</td>"
+ "</tr>")
});

Error when trying to get the value of an input number with JavaScript

I am trying to simulate a shopping cart with just Javascript, but I'm getting an error everytime I update the value of the input number to update the table: "Uncaught TypeError: Cannot read property 'value' of undefined"
When I use console.log to see the value, it shows the value so I don't know why it says it cannot read the property value.
I have no idea what's wrong. Here is my function to add the items to the table:
function addRowsToTable(product_value, product_name, product_image, product_price, product_qty, sub_total){
//console.log(value);
if (sessionStorage.Total_Items > 0){
var table = document.getElementById("shop-table");
var row = table.insertRow(1);
row.innerHTML = "<tr>\n" +
" <td>\n" +
" <button value=\"" + product_value + "\" onclick=\"deleteRowFromTable(this);\">Remove</button>\n" +
" </td>\n" +
" <td>\n" +
" <img src=\""+ product_image+"\" style=\"width: 60px; height: 80px;\">\n" +
" </td>\n" +
" <td>" + product_name + "</td>\n" +
" <td>\n" +
" <input id=\"" + product_value + "\" type=\"number\" name=\"quantity\" min=\"0\" max=\"20\" value=\""+ product_qty +"\" onclick=\"updateFromShoppingCart(this);\">\n" +
" </td>\n" +
" <td>"+ product_price +"</td>\n" +
" <td>"+ sub_total+"</td>\n" +
" </tr>";
}
}
Here is my function to update the table from after I change the value of input number tag by using the onchange event:
function updateFromShoppingCart(element){
saveItemsQtyToStorage();
loadItemsQtyFromStorage();
console.log(element.value);
if(element.value > 0){
var table = document.getElementById("shop-table");
var new_quatity = element.value;
var id = element.id;
ItemsQty[id] = new_quatity;
var parentRowIndex = element.parentNode.parentNode.rowIndex;
//console.log(ItemsQty[id]);
table.rows[parentRowIndex].cells[5].innerText = ItemsQty[id] * ItemPrice[id];
saveItemsQtyToStorage();
loadItemsQtyFromStorage();
updateFromShoppingCart();
cartTotalPrice();
}
else{
deleteRowFromTable(ele);
}
}
Here is the HTML Code of the Table"
<table id="shop-table">
<tr>
<th>Remove Product</th>
<th>Product Image</th>
<th>Product Description</th>
<th>Qty.</th>
<th>Unit Price</th>
<th>Subtotal</th>
</tr>
</table>
Picture of the error:
Thanks.
You're recursively calling updateFromShoppingCart(); without passing the element parameter, so when it executes, element is undefined, and you will get that error on the console.log line.
If you remove the recursive call, it should work.

change font color of a row in jquery ajax table

I want to change the font color of values in a row based on the condition that applied inside the function. If the TotalStudent is greater than room capacity, the student information gets added to the table with the font color of red. Below is what I've tried. I've used ajax method and within success function I'm generating table to insert values. The condition is running fine.
Create.cshtml
$.ajax({
type: "POST",
url: '#Url.Action("AddStudent", "Student")',
data: model,
dataType: "json",
success: function(data) {
$('#dialog').dialog('close');
alert(data.countstudent);
alert(data.roomcapacity);
//var student = data.countstudent;
if (data.countstudent > data.roomcapacity) {
var tblEndrolled = $("#tblEnrolled");
$.each(data.record, function(index, item) {
$('.status').css("color", "red");
var tr = $("<tr></tr>");
tr.html(("<td>" + '<input type="submit" id="' + item.Id + '" value="Remove" class="" />' + "</td>") +
" " + ("<td class = 'status'>" + item.FirstName + "</td>") +
" " + ("<td>" + item.LastName + "</td>") +
" " + ("<td>" + item.EmailAddress + "</td>") +
" " + ("<td>" + item.Phone + "</td>"));
tblEndrolled.append(tr);
});
}
<div>
<strong style = "font-size:20px" > Enrolled Students: < /strong>
<table class = "table table-bordered table-responsive table-hover" id="tblEnrolled">
<tr>
<th>Action</th>
#*<th>User Id</th>
*#<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</table>
</div>
It needs two modication :
1st just add class status at the creation of tr.
2nd apply css style at the end of each loop, like below:
.
//var student = data.countstudent;
if (data.countstudent > data.roomcapacity) {
var tblEndrolled = $("#tblEnrolled");
$.each(data.record, function(index, item) {
var tr = $("<tr class = 'status'></tr>");
tr.html(("<td>" + '<input type="submit" id="' + item.Id + '" value="Remove" class="" />' + "</td>") +
" " + ("<td >" + item.FirstName + "</td>") +
" " + ("<td>" + item.LastName + "</td>") +
" " + ("<td>" + item.EmailAddress + "</td>") +
" " + ("<td>" + item.Phone + "</td>"));
tblEndrolled.append(tr);
});
$('.status').css("color", "red");
}
I hope it will fulfill your requirement.
$('.status').css("color", "red"); just change color on all elements which already had class status. So, if your change $('.status')... and row additional your new row will have red color. Indeed same colors will have all elements with status class.
Put the class in tr tag
var tr = $("<tr class = 'status'>></tr>");
Remove this ( use are setting style before you are generation the tr)
$('.status').css("color", "red");
And add class in css file
.status {
color:red;
}
OR
set style after tr is appended to table.
tblEndrolled.append(tr);
$('.status').css("color", "red");
Demo
.status {
color:red;
}
<table class = "table table-bordered table-responsive table-hover" id="tblEnrolled">
<tr>
<th>Action</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr class="status">
<td>test</td>
<td>test</td>
<td>test</td>
<td>test</td>
</tr>
</table>

How to make the table in javascript

I have this code to make the data available in table format but the table head and row appear as two different body, how do i work with that
$("#container").html("<table> <th>Name</th> <th>Address</th> <th>Sex</th> <th>Email</th>")
for (var i = 0; i < data.length; i++) {
$("#container").append("<tr><td>" +
data[i].name + "</td><td>" +
data[i].address + "</td><td>" +
data[i].sex + "</td><td>" +
data[i].email + "</td><tr>"
);
}
$("container").append("</table>")
This is what I get
I want the whole table, not two seperate buddies.
var htmlTable = '<table><tr><th>Name</th><th>Adress</th><th>Sex</th> <th>Email</th></tr>';
for(var i = 0; i < data.length; i++) {
htmlTable += '<tr><td>' + data[i].name + '</td><td>' + data[i].adress + '</td><td>' + data[i].sex + '</td><td>' + data[i].email + '</td></tr>';
}
htmlTable += '</table>';
$('#container').html(htmlTable);
Add the table to the DOM at once, otherwise the browser will have problems rendering it.
You can't append <table> and </table> separately, appending DOM elements (by setting innerHTML behind the scene) is not the same as string concatenation. Browser detects invalid markup and fixes it accordingly by adding missing parts of the table. So as the result you get one table after first append, and in the loop you are appending rows into #container, not the table, which is rendered incorrectly.
To fix try something like this:
var $table = $("#container").html("<table><tr><th>Name</th><th>Address</th><th>Sex</th><th>Email</th></tr></table>");
for (var i = 0; i < data.length; i++) {
$table.append("<tr><td>" + data[i].name + "</td><td>" + data[i].address + "</td><td>" + data[i].sex + "</td><td>" + data[i].email + "</td></tr>");
}
Note, I also cached $table variable so you don't query DOM in each iteration.
Also pay attention to closing tags, in your code you have couple of problems like <tr> where it should be </tr>.
You need to add <tr> too for <th>:
$("#container").html("<table> <tr><th>Name</th> <th>Address</th> <th>Sex</th> <th>Email</th></tr></table>")

How to stop from appeding the the value to just updating the value in jQuery?

I am trying to prevent the player from getting added again with the new value, rather I would like to just update the quantity..
HTML
<div class="playerTypeBlock" data-player-type-id="1" data-player-value="10.00">
<div class="heading">Ninja</div>
<div class="price">$10</div> <a class="addToTeam" href="#">Add player</a>
</div>
<hr>
<div class="playerTypeBlock" data-player-type-id="2" data-player-value="20.25">
<div class="heading">Samurai</div>
<div class="price">$20.25</div> <a class="addToTeam" href="#">Add player</a>
</div>
<hr>
<table class="teams" border="1">
<thead>
<tr>
<th>Players</th>
<th>Quantity</th>
</tr>
</thead>
<tbody class="totalPlayers"></tbody>
</table>
<div class="total">
<span>Total: $</span>
<span class="amount" id="totalvalue">0.00</span>
</div>
I tried using this when appending the table row, but not getting the desired result
JavaScript
var addToTeam = document.getElementsByClassName('addToTeam'),
parentElement = document.getElementsByClassName('playerTypeBlock'),
playerName = document.getElementsByClassName('heading'),
totalVal = document.getElementById('totalvalue'),
tableBody = document.querySelector('.totalPlayers');
var updatePlayers = function (evt) {
evt.preventDefault();
var amount = totalVal.innerHTML,
productId = this.parentElement.getAttribute('data-player-type-id'),
productPrice = this.parentElement.getAttribute('data-player-value'),
playerName = this.parentNode.querySelector('.heading').innerHTML,
updateTotal = parseFloat(amount) + parseFloat(productPrice);
var quantity = parseInt($(this).data('click'), 10) || 0;
quantity++;
$(this).data('click', quantity);
totalVal.innerHTML = Math.round(updateTotal * 100) / 100;
//adding the the table row here...
$('table .totalPlayers').append('<tr><td>' + playerName + '</td><td>' + quantity + ' </td></tr>');
};
for (var i = 0; i < addToTeam.length; i++) {
addToTeam[i].addEventListener('click', updatePlayers);
}
See Demo
Check quantity and append new row if it's 1 otherwise modify quantity cell:
if (quantity > 1) {
$('table .totalPlayers').find('#player-' + playerId + ' .quantity').text(quantity);
}
else {
$('table .totalPlayers').append('<tr id="player-' + playerId + '"><td>' + playerName + '</td><td class="quantity">' + quantity + ' </td></tr>');
}
Demo: http://jsfiddle.net/zx65uv8a/12/
This line the problem?
$('table .totalPlayers').append(
'<tr><td>' + playerName + '</td>' +
'<td>' + quantity + ' </td></tr>');
You are using append() so you'll always be adding and not replacing.
If you can add something unique to a class or id then you can replace it that way. i.e.
$('table .totalPlayers').append(
'<tr id="' + playerId + '">' +
'<td>' + playerName + '</td>' +
'<td class="quantity">' + quantity + ' </td></tr>');
Then to update
$('#' + playerId + ' .quantity').html(New value here);

Categories

Resources