Dynamically add or delete rows in a table using jQuery - javascript

Dynamically add or delete rows in a table using jQuery but how to keep data in arrays after removing a row and don't get the totalSum when I add new row after deleting previous one .row add sucessfully and get initial sum but aftre remove operation i get NAN total sum
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
function validation() {
if (document.getElementById(txt_item).value == "")
alert("Please Enter a Item name");
return false;
if (document.getElementById(txt_price).value == "")
alert("Please Enter Price");
return false;
if (document.getElementById(txt_quantity).value == "")
alert("Please Enter Quantity");
return false;
}
</script>
<script>
var itemCount = 0;
$(document).ready(function () {
var array = [];
$("#txt_item").focus();
$("#txt_quantity").keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9) {
var table = "";
var arr = {
"Row_ID": itemCount,
"TXT_ITEM": $("#txt_item").val(),
"TXT_PRICE": $("#txt_price").val(),
"TXT_QUANTITY": $("#txt_quantity").val(),
"TOTAL_AMOUNT": $("#txt_price").val() * $("#txt_quantity").val()
}
array.push(arr);
itemCount++;
table = "<tr id='" + itemCount + "'><td>" + arr['TXT_ITEM'] + "</td><td id='price_"+itemCount+"'>" + arr['TXT_PRICE'] + "</td><td><input type='text' id='quantity_"+itemCount+"' value='" + arr['TXT_QUANTITY'] + "'></td><td id='" + itemCount + "_total'>" + parseInt(arr['TXT_PRICE']) * parseInt(arr['TXT_QUANTITY']) + "</td><td><input type='button' id='" + itemCount + "' class='btn' value='Remove'></td></tr>";
$("#test1").append(table);
totalSum();
$(".btn").click(function () {
var buttonId = $(this).attr("id");
//var value_quantity = $(this).val();
//buttonId = buttonId.replace("tr", "").trim();
//var value_price = $("#price_" + buttonId).text();
//var value_total_price = parseInt($("#"+buttonId+"_total").text());
//var tamount=parseInt($("#total_amount").text());
//$("#total_amount").text(tamount - value_total_price);
////alert(tamount);
//alert(value_total_price);
$("#" + buttonId).remove();
array.splice(buttonId - 1, 1);
//itemCount--;
totalSum();
Array_IDs();
itemCount = array.length + 1;
});
$("#quantity_" + itemCount).keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9)
var value_quantity = $(this).val();
var rowId = $(this).closest('tr').attr('id');
rowId = rowId.replace("tr", "").trim();
var value_price = $("#price_" + rowId).text();
if (value_quantity >= 0)
{
$("#" + rowId+"_total").text(value_price * value_quantity);
totalSum();
}
});
$("#txt_item").val("");
$("#txt_price").val("");
$("#txt_quantity").val("");
}
function totalSum() {
var total = 0;
var rows = array.length;
for (var i = 1; i <= rows; i++) {
total += parseInt($("#" + i + "_total").text());
//total += parseInt(array[i].TXT_PRICE * array[i].TXT_QUANTITY);
}
$("#total_amount").text(total);
//alert(total);
}
function Array_IDs()
{
for (var i = 0; i < array.length; i++) {
array[i].Row_ID = i + 1;
//alert(i);
}
//$("#test1 tr").remove();
}
});
});
</script>
</head>
<body>
<table id="test1">
<tr>
<td>Item Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total Amount</td>
<td>Action</td>
</tr>
<tfoot>
<tr>
<td><input type="text" id="txt_item" /></td>
<td><input type="text" id="txt_price" /></td>
<td><input type="text" id="txt_quantity" /></td>
<td id="total_price" align="center"></td>
</tr>
<tr>
<td></td>
<td>#*<input type="button" id="add_button" value="Add Row" />*#</td>
<td align="right">Total Amount:</td>
<td id="total_amount" align="center"></td>
</tr>
</tfoot>`enter code here`
</table>
<table id="test2" width="50%"></table>
</body>
</html>

<html>
<head>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.min.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
function validation() {
if (document.getElementById(txt_item).value == "")
alert("Please Enter a Item name");
return false;
if (document.getElementById(txt_price).value == "")
alert("Please Enter Price");
return false;
if (document.getElementById(txt_quantity).value == "")
alert("Please Enter Quantity");
return false;
}
var itemCount = 0;
$(document).ready(function () {
var array = [];
$("#txt_item").focus();
$("#txt_quantity").keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9) {
var table = "";
var iPrice = 0;
if ($("#txt_price").val() == "" || isNaN($("#txt_price").val())) {
iPrice = 0;
}
else {
iPrice = parseInt($("#txt_price").val(), 10);
}
var iQuatity = 0;
if ($("#txt_quantity").val() == "" || isNaN($("#txt_quantity").val())) {
iQuatity = 0;
}
else {
iQuatity = parseInt($("#txt_quantity").val(), 10);
}
szTotal = iPrice * iQuatity;
var arr = {
"Row_ID": itemCount,
"TXT_ITEM": $("#txt_item").val(),
"TXT_PRICE": iPrice,
"TXT_QUANTITY": iQuatity,
"TOTAL_AMOUNT": szTotal
}
array.push(arr);
itemCount++;
table = "<tr id='" + itemCount + "'><td>" + arr['TXT_ITEM'] + "</td><td id='price_" + itemCount + "'>" + arr['TXT_PRICE'] + "</td><td><input type='text' id='quantity_" + itemCount + "' value='" + arr['TXT_QUANTITY'] + "'></td><td class='td_total' id='" + itemCount + "_total'>" + parseInt(arr['TXT_PRICE']) * parseInt(arr['TXT_QUANTITY']) + "</td><td><input type='button' id='" + itemCount + "' class='btn' value='Remove'></td></tr>";
$("#test1 tbody").append(table);
totalSum();
$(".btn").click(function () {
var buttonId = $(this).attr("id");
//var value_quantity = $(this).val();
//buttonId = buttonId.replace("tr", "").trim();
//var value_price = $("#price_" + buttonId).text();
//var value_total_price = parseInt($("#"+buttonId+"_total").text());
//var tamount=parseInt($("#total_amount").text());
//$("#total_amount").text(tamount - value_total_price);
////alert(tamount);
//alert(value_total_price);
$("#" + buttonId).remove();
array.splice(buttonId - 1, 1);
//itemCount--;
totalSum();
Array_IDs();
itemCount = array.length + 1;
});
$("#quantity_" + itemCount).keydown(function (e) {
var code = e.keyCode || e.which
if (code === 9)
var value_quantity = 0;
if ($(this).val() != "" && !isNaN($(this).val()))
{
value_quantity = parseInt($(this).val(),10)
}
var rowId = $(this).closest('tr').attr('id');
rowId = rowId.replace("tr", "").trim();
var value_price = 0;
if ($("#price_" + rowId).text() != "" && !isNaN($("#price_" + rowId).text())) {
value_price=parseInt($("#price_" + rowId).text(),10);
}
if (value_quantity >= 0) {
$("#" + rowId + "_total").text(value_price * value_quantity);
totalSum();
}
});
$("#txt_item").val("");
$("#txt_price").val("");
$("#txt_quantity").val("");
}
function totalSum() {
var total = 0;
//var rows = array.length;
//for (var i = 1; i <= rows; i++) {
// total += parseInt($("#" + i + "_total").text());
// //total += parseInt(array[i].TXT_PRICE * array[i].TXT_QUANTITY);
//}
$('.td_total').each(function () {
if (!isNaN($.trim($(this).text())) && $.trim($(this).text()) != "")
{
total = total+parseInt($(this).text(),10)
}
});
$("#total_amount").text(total);
//alert(total);
}
function Array_IDs() {
for (var i = 0; i < array.length; i++) {
array[i].Row_ID = i + 1;
//alert(i);
}
//$("#test1 tr").remove();
}
});
});
</script>
</head>
<body>
<table id="test1">
<tr>
<td>Item Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total Amount</td>
<td>Action</td>
</tr>
<tbody></tbody>
<tfoot>
<tr>
<td><input type="text" id="txt_item" /></td>
<td><input type="text" id="txt_price" /></td>
<td><input type="text" id="txt_quantity" /></td>
<td id="total_price" align="center"></td>
</tr>
<tr>
<td></td>
<td>#*<input type="button" id="add_button" value="Add Row" />*#</td>
<td align="right">Total Amount:</td>
<td id="total_amount" align="center"></td>
</tr>
</tfoot>`enter code here`
</table>
<table id="test2" width="50%"></table>
</body>
</html>

Related

How do I add up all numbers into one variable and show it?

Whenever I try doing the code myself, nothing shows up after I run the function, I'm wanting to add all the numbers from 'fkWynik'.
function mat_WypiszLiczbyNaturalne() {
var T = "";
T = document.getElementById('fkEdit').value;
if ((T.trim() != "") && (Number(T) > 0)) {
var S = "";
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
}
document.getElementById('fkWynik').value = S.substr(2) + " = ";
} else {
document.getElementById('fkWynik').value = "Prosze wprowadzic liczbe!";
}
}
<html>
<body>
<FORM NAME="formularz1" ACTION="">
<TABLE BORDER="0">
<INPUT TYPE="number" ID="fkEdit" STYLE="height:24px; width:55px;">
<INPUT TYPE="button" ID="fkWykonaj" VALUE="Wykonaj" onClick="mat_WypiszLiczbyNaturalne();"> </TD>
</TR>
<TR><TD> <INPUT TYPE="text" ID="fkWynik" STYLE="width:545px; height:24px;" READONLY> </TD></TR>
</TABLE>
</FORM>
</body>
</html>
You need to add the numbers together and concat it to the string:
function mat_WypiszLiczbyNaturalne() {
var T = "";
T = document.getElementById('fkEdit').value;
if ((T.trim() != "") && (Number(T) > 0)) {
var S = "";
var total = 0
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
total += I;
}
document.getElementById('fkWynik').value = S.substr(2) + " = "+total.toString();
} else {
document.getElementById('fkWynik').value = "Prosze wprowadzic liczbe!";
}
}
<html>
<body>
<FORM NAME="formularz1" ACTION="">
<TABLE BORDER="0">
<INPUT TYPE="number" ID="fkEdit" STYLE="height:24px; width:55px;">
<INPUT TYPE="button" ID="fkWykonaj" VALUE="Wykonaj" onClick="mat_WypiszLiczbyNaturalne();"> </TD>
</TR>
<TR><TD> <INPUT TYPE="text" ID="fkWynik" STYLE="width:545px; height:24px;" READONLY> </TD></TR>
</TABLE>
</FORM>
</body>
</html>
The following should work if your HTML code contains an element with the property id="fkWynik"
function mat_WypiszLiczbyNaturalne() {
var elem = document.getElementById('fkEdit');
if(!elem) {
console.error("No element with id 'fkEdit' in the page.");
return;
}
var T = elem.value;
var value = "";
if (T && !isNaN(Number(T))) { // if T not null, not empty, not undefined, not 0 and is a number
var S = "";
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
}
value = S.substr(2) + " = ";
} else {
value = "Proszę wprowadzić liczbę!";
}
console.log("value: " + value);
document.getElementById('fkWynik').value = value;
}
mat_WypiszLiczbyNaturalne();

How can I set up a button handler to remove a parent table row?

I have this HTML & jQuery project, and everything currently works perfectly for what I want them to do. What I need right now is to add a Delete/Remove Button that is linked to this line:
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
As you can see the buttons are visible only if you click the add button and create a new TR with values.
I tried creating a jQuery function:
function removeThis(a) {
$('tr-' + 'a').remove();
}
But of course, it's not doing what I need it to do.
Can anyone help me resolving this?
Thanks in advance.
$(document).ready(function () {
$('.buttons').on('click', 'button.hide', function () {
console.log('hide');
$('form').hide();
});
$('.buttons').on('click', 'button.add', function () {
console.log('add');
var edit = $('#edit');
editRow = $('#editRow');
edit.show();
if (!($('#addNew').length)) {
edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
}
if (editRow) {
editRow.remove();
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
});
$('#show').click(function () {
//$('form').show();
//$('#btd1').val('Vlad');
//$('#btd2').val('Andrei');
//$('#btd3').val('vTask');
// $('#btd4').val('Ceva');
//$('#btd5').val('Alceva');
});
});
function edit(a) {
var edit = $('#edit');
addNew = $('#addNew');
editRow = $('#editRow');
edit.show();
if (addNew) {
addNew.remove();
}
if (editRow.length) {
editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
} else {
edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
}
$.each($('.tr-' + a).find('td'), function (key, val) {
$('form#edit input[type=text]').eq(key).val($(val).text());
});
}
function save(a) {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please complete all the colums' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
$('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
$('#editRow').remove();
}
}
function addNewTr() {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table tbody').append('' +
'<tr class="tr-' + tr.length + '">' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons">' +
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
'<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
'</td >' +
'</tr>' +
'');
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
}
}
function removeThis(a) {
$('tr-' + 'a').remove();
}
<!DOCTYPE html>
<html >
<head >
<link href="../css/vtask.css" rel="stylesheet">
<title >vTask</title >
<h1 id="hh1">[<a id="vt1">vTask</a>]</h1>
</head >
<body>
<table class="greenTable">
<tr><td colspan="6"><form id="edit" action="" method="post" hidden >
<label for="btd1" ></label >
<input type="text" name="Name" id="btd1" value="" placeholder="Name">
<label for="btd2" ></label >
<input type="text" name="Secondary Name" id="btd2" value="" placeholder="Secondary Name">
<label for="btd3" ></label >
<input type="text" name="Email" id="btd3" value="" placeholder="Email">
<label for="btd4" ></label >
<input type="text" name="Telephone" id="btd4" value="" placeholder="Telephone">
<label for="btd5" ></label >
<input type="text" name="Password" id="btd5" value="" placeholder="Password">
</form ></td></tr>
<tr>
<td width="10%">Name</td>
<td width="10%">Secondary Name</td>
<td width="10%">Email</td>
<td width="10%">Telephone</td>
<td width="10%">Password</td>
<td class="buttons" width="20%"><button class="add" >Add</button >
<button class="hide" >Hide</button ></td>
</tr>
</table >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body >
</html >
I don't want any of the other functions to be deleted.
BTW the Delete button is already added with ID removeThis.
Thank you very much in advance.
You can achieve this without jQuery at all, and I highly recommend that.
function removeThis(e){
const parentTd = e.parentNode;
const parentTr = parentTd.parentNode;
const parentTable = parentTr.parentNode;
return parentTable.removeChild(parentTr);
}
And on your button you do
<button onClick='removeThis(this)'>Delete me</button>
This way you create a testable and reusable function that you can use to remove all DOM Elements.
Oh, and by the way, this way you work from inside-out rather than querying the whole document for the element intended to remove.
Your example function below builds a string 'tr-' + 'a' which will always just look for "tr-a":
function removeThis(a) {
$('tr-' + 'a').remove();
}
Just remove the quotes from around 'a':
function removeThis(a) {
$('tr-' + a).remove();
}
Remove the quotes around the letter 'a' so you can use the variable there:
function removeThis(a) {
$('.tr-' + a).remove();
}
You should also consider using a different way to number the table rows. The row numbers will start to get reused if you delete a row and then add a new one:
Row 0, Row 1, Row 2, Row 3, Row 4
Add row. There are 5 rows, so the new row is row 5.
Row 0, Row 1, Row 2, Row 3, Row 4, Row 5
Remove row 1.
Row 0, Row 2, Row 3, Row 4, Row 5
Add row. There are 5 (!!!) rows, so the new row is (also!!!) row 5.
Row 0, Row 2, Row 3, Row 4, Row 5, Row 5
Instead of getting a new value for tr every time you add a row, instead consider a global variable that you increment every time you add a row:
var rowCounter = 0;
function addNewTr() {
//snip
rowCounter++;
$('table tbody').append('' +
'<tr class="tr-' + rowCounter + '">' +
//snip
}
I think you just need to remove the quotes from 'a':
function removeThis(a) {
$('.tr-' + a).remove();
}
EDIT: This snippet is totally working! I did need to add a dot before 'tr' since it is a class.
$(document).ready(function () {
$('.buttons').on('click', 'button.hide', function () {
console.log('hide');
$('form').hide();
});
$('.buttons').on('click', 'button.add', function () {
console.log('add');
var edit = $('#edit');
editRow = $('#editRow');
edit.show();
if (!($('#addNew').length)) {
edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
}
if (editRow) {
editRow.remove();
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
});
$('#show').click(function () {
//$('form').show();
//$('#btd1').val('Vlad');
//$('#btd2').val('Andrei');
//$('#btd3').val('vTask');
// $('#btd4').val('Ceva');
//$('#btd5').val('Alceva');
});
});
function edit(a) {
var edit = $('#edit');
addNew = $('#addNew');
editRow = $('#editRow');
edit.show();
if (addNew) {
addNew.remove();
}
if (editRow.length) {
editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
} else {
edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
}
$.each($('.tr-' + a).find('td'), function (key, val) {
$('form#edit input[type=text]').eq(key).val($(val).text());
});
}
function save(a) {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please complete all the colums' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
$('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
$('#editRow').remove();
}
}
function addNewTr() {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table tbody').append('' +
'<tr class="tr-' + tr.length + '">' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons">' +
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
'<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
'</td >' +
'</tr>' +
'');
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
}
}
function removeThis(a) {
alert('.tr-'+a);
$('.tr-' + a).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html >
<head >
<link href="../css/vtask.css" rel="stylesheet">
<title >vTask</title >
<h1 id="hh1">[<a id="vt1">vTask</a>]</h1>
</head >
<body>
<table class="greenTable">
<tr><td colspan="6"><form id="edit" action="" method="post" hidden >
<label for="btd1" ></label >
<input type="text" name="Name" id="btd1" value="" placeholder="Name">
<label for="btd2" ></label >
<input type="text" name="Secondary Name" id="btd2" value="" placeholder="Secondary Name">
<label for="btd3" ></label >
<input type="text" name="Email" id="btd3" value="" placeholder="Email">
<label for="btd4" ></label >
<input type="text" name="Telephone" id="btd4" value="" placeholder="Telephone">
<label for="btd5" ></label >
<input type="text" name="Password" id="btd5" value="" placeholder="Password">
</form ></td></tr>
<tr>
<td width="10%">Name</td>
<td width="10%">Secondary Name</td>
<td width="10%">Email</td>
<td width="10%">Telephone</td>
<td width="10%">Password</td>
<td class="buttons" width="20%"><button class="add" >Add</button >
<button class="hide" >Hide</button ></td>
</tr>
</table >
<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body >
</html >

Unable to retieve the particular value of cell on table using javascript

I am using the following code to retrieve the values of a particular cell of a table.:
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].document.getElementsByTagName("input").item(1).value;
var lifecycycleattr1 = r.cells[0].document.getElementsByTagName("input").item(2).value;
var stateattr1 = r.cells[0].document.getElementsByTagName("input").item(3).value;
}
}
}
and my html code is :
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
I want to retrieve each value of a particular.
Its just an example.I have more thane two rows for which i need for loop to get the values of each cell.
See if this points you in the right direction:
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].innerText;
var lifecycycleattr1 = r.cells[1].innerText;
var stateattr1 = r.cells[2].innerText;
alert('catname1: ' + catname1 + '\r\n' +
'lifecycycleattr1: ' + lifecycycleattr1 + '\r\n' +
'stateattr1: ' + stateattr1 + '\r\n');
}
}
}
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
<input type="button" onclick="addCatAttr()" value="Click me" />
This can help better...
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].innerHTML;
var lifecycycleattr1 = r.cells[1].innerHTML;
var stateattr1 = r.cells[2].innerHTML;
alert('catname1: ' + catname1 + '\r\n' +
'lifecycycleattr1: ' + lifecycycleattr1 + '\r\n' +
'stateattr1: ' + stateattr1 + '\r\n');
}
}
}
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
<input type="button" onclick="addCatAttr()" value="Click me" />
You need to apply two for loops one for table length and the other for the each td in tr. This is the code.
var table = document.getElementById('tblAttributes1'),
rows = table.getElementsByTagName('tr');
for (var i = 0; i< rows.length; i++) {
var tds = rows[i].getElementsByTagName('td');
for(var x=0;x<tds.length;x++){
console.log(tds[x].innerHTML);
}
And the fiddle is-
http://jsfiddle.net/09q6n3m2/16/

How to remove the duplicates for append in my html?

I have create javascript to calulate the total of ext. form json but I have problem is it append twice to #total div I don't know what cause maybe because of renderTable function.can someone help me ??
HTML
<div data-role="collapsible" data-collapsed="true" id="poInfos">
<h3 id="poInfo"></h3>
<table data-role="table" id="productOrders" data-mode="reflow">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Price</th>
<th>Qty.</th>
<th>Ext.</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<div id="total">
</div>
</div>
</div>
</div>
javascript
//render table view all PO for vendor
function renderTable(data){
var $table = $('#productOrders tbody');
var plist = data[0].pslList;
for(var i in plist) {
var row = $('<tr><td>' + plist[i].prodcd + '</td><td>' + plist[i].prodname + '</td><td class="dollars">' + numberToCurrency(plist[i].price) + '</td><td>' + plist[i].qty + '</td><td>' + numberToCurrency(plist[i].ext) + '</td></tr>');
$table.append(row);
calculateTotal(data);
}
}
//calculateTotal
function calculateTotal(data)
{
var $totalDiv = $('#total');
var tax = 0.00;
var sub = 0.00;
var totalsub_tax = 0.00;
var plist = data[0].pslList;
for(var i in plist) {
sub += plist[i].ext;
totalsub_tax = sub +tax;
}
$totalDiv.append("<strong>Sub:</strong>"+numberToCurrency(sub)+"<br/><strong>Total:</strong>"+numberToCurrency(totalsub_tax) +"<br/>");
}
//convert numberToCurrency
function numberToCurrency(amount) {
var thousandsSeparator = ","
var currencyNum = "";
var amountString = amount.toString();
var digits = amountString.split("");
var countDigits = digits.length;
var revDigits = digits.reverse();
for(var i=0; i<countDigits; i++) {
if ((i%3 == 0) && (i !=0)) {
currencyNum += thousandsSeparator+revDigits[i];
} else {
currencyNum += digits[i];
}
};
var revCurrency = currencyNum.split("").reverse().join("");
var finalCurrency = "$"+revCurrency;
return finalCurrency;
}
});
You're running the function calculateTotal() for EACH item instead of after the items have been dealt with.
for(var i in plist) {
var row = $('<tr><td>' + plist[i].prodcd + '</td><td>' + plist[i].prodname + '</td><td class="dollars">' + numberToCurrency(plist[i].price) + '</td><td>' + plist[i].qty + '</td><td>' + numberToCurrency(plist[i].ext) + '</td></tr>');
$table.append(row);
// not here calculateTotal(data);
}
calculateTotal(data); // here
Your call to calculateTotal(data) is within the loop over plist. You should move it outside.

Problems with creating dynamically <select/>

<script type="text/javascript">
var a = new Array();
function obj(type, value) {
this.type = type;
this.value = value;
this.toStr = toStr
}
function toStr() {
if (this.type == "select") {
var temp = "";
var arr = this.value.split("/");
for (i = 0; i < arr.length; i++) {
temp += "<option>" + arr[i] + "</option>"
}
return "<select>" + temp + "</select><br>";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "'><br>";
}
function addObj(type) {
var sel = parent.frames["left"].document.form1.q.value;
for (i = 0; i < sel; i++)
a[a.length] = new obj(type,
parent.frames["left"].document.form1.caption_text.value,
a.length);
paint();
parent.frames["left"].document.form1.caption_text.value = "";
}
function paint() {
parent.frames["right"].document.open()
for (i = 0; i < a.length; i++)
parent.frames["right"].document.writeln(a[i].toStr())
parent.frames["right"].document.close()
}
</script>
<form name=form1>
<table>
<tr>
<td><input type="button" style="width: 150px" value="Add Button" onClick="addObj('button')"><br />
<input type="button" style="width: 150px" value="Add TexBox" onClick="addObj('text')" /><br />
<input type="button" style="width: 150px" value="Add Select" onClick="addObj('select')" /></td>
<td>Text : <br /> Number of adding elements:<br /></td>
<td><input type="text" name="caption_text" style="width: 150px"> <br /> <select
NAME=q size=1 style="width: 150px">
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
</table>
</FORM>
Code is corrupting when creating select elements.
What's wrong with this code?
Thanks in advance.
Your i variables are missing a var declaration. All loops use the same counter, which means that nested loops will break horribly. My suggestion:
var a = [];
function FormElement(type, value) {
this.type = type;
this.value = value;
}
FormElement.prototype.toString = function toStr(){
if (this.type == "select") {
var arr = this.value.split("/");
for (var i = 0; i < arr.length; i++) {
arr[i] = "<option>" + arr[i] + "</option>"
}
return "<select>" + arr.join("") + "</select><br />";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "' /><br />";
};
function addObj(type) {
var form = parent.frames["left"].document.form1;
var sel = form.q.value;
for (var i = 0; i < sel; i++)
a.push(new FormElement(type, form.caption_text.value);
paint();
form.caption_text.value = "";
}
function paint() {
var doc = parent.frames["right"].document;
doc.open();
doc.write(a.join("\n"));
doc.close();
}

Categories

Resources