How to calculate some field in one row using jquery - javascript

I have created some code to calculate some fields in row. But i added some function, so i can add row dynamically using jquery.
This is my source code on my codepen
Click here!
this is my function to calculate qtyItem column and price columns
$("tbody").keyup(function() {
var qtyItem = parseFloat($("#qtyItem").val());
var price = parseFloat($("#price").val());
var subTotal = qtyItem * price;
$("#subTotal").attr("value", subTotal);
});
the problem is when i try to calculate the 1st row, it's work fine. but the others not affected by the function in my script.

IDs must be unique, so avoid dulicated. For this you can use Template_literals (see the ${nextIdx} in the snippet).
You need to consider NaN values returned by parseFloat
Now, in your price event handler you can change strategy:
get the parent row
find an element looking for it in the children having an id starting with
The new code is now:
$(".addItem").click(function(e) {
var nextIdx = $("table tbody tr").length + 1;
var row = `<tr>
<td><input type="text" class="form-control" name="itemName" id="itemName${nextIdx}"></td>
<td><input type="number" class="form-control" name="qtyItem" id="qtyItem${nextIdx}"></td>
<td><input type="number" class="form-control" name="price" id="price${nextIdx}"></td>
<td><input type="number" class="form-control" name="subTotal" id="subTotal${nextIdx}" readonly></td>
</tr>`;
$("table").append(row);
});
//subTotal count
$("tbody").keyup(function(e) {
var crow = $(e.target).closest('tr'); // get parent row
// find qtyItem in the children
var qtyItem = parseFloat(crow.find("[id^=qtyItem]").val()) || 0;
// find price in the children
var price = parseFloat(crow.find("[id^=price]").val()) || 0;
var subTotal = qtyItem * price;
crow.find("[id^=subTotal]").attr("value", subTotal);
});
table,td, th{
border: 2px, solid, black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#">
<label for="username">Username</label>
<input id="username" type="text" placeholder="Input your username"> <br>
<label for="date">Date</label>
<input id="date" type="date"> <br>
<label for="itemSold">Item List</label>
<table>
<thead>
<tr>
<th>Item</th>
<th>Qty</th>
<th>price</th>
<th>SubTotal</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" class="addItem">Add Item</button>
</form>

You can do it without use id attribute, instead that u can use the name attribute for each row.
$(document).ready(function() {
//add row on button click
$(".addItem").click(function() {
var row = `<tr>
<td><input type="text" class="form-control" name="itemName"></td>
<td><input type="number" class="form-control" name="qtyItem"></td>
<td><input type="number" class="form-control" name="price"></td>
<td><input type="number" class="form-control" name="subTotal" readonly></td>
</tr>`;
$("table").append(row);
});
const $tBody = $('tbody')
//subTotal count
$tBody.on("keyup", 'input[type="number"]', function() {
let $parentTr = $(this).closest("tr");
let qtyItem = parseFloat($parentTr.find('td input[name="qtyItem"]').val());
let price = parseFloat($parentTr.find('td input[name="price"]').val());
if (!isNaN(qtyItem) && !isNaN(price)) {
let subTotal = qtyItem * price;
$parentTr.find('td input[name="subTotal"]').attr("value", subTotal);
}
});
});
table,td, th{
border: 2px, solid, black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#">
<label for="username">Username</label>
<input type="text" placeholder="Input your username"> <br>
<label for="date">Date</label>
<input type="date"> <br>
<label for="itemSold">Item List</label>
<table>
<thead>
<tr>
<th>Item</th>
<th>Qty</th>
<th>price</th>
<th>SubTotal</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" class="addItem">Add Item</button>
</form>

Related

jQuery function is not working on newly added row

I want to make simple real time calculator without page refresh with jquery.
I added dynamic table row with jquery and applied some method in the input fields but that is not working perfectly in newly added rows.
newly added rows are only working when I change something in the default rows.
Here is my html codes:
<button type="button" id="addBillingRow" class="btn btn-success btn-sm fa fa-plus fa-3x float-right">add</button>
<table class="table table-bordered" id="dynamic_field_shipping">
<thead>
<tr>
<th width="10%">Date</th>
<th width="20%">Purpose</th>
<th width="20%">Amount</th>
<th width="10%">Quantity</th>
<th width="30%">Total</th>
<th width="10%">#</th>
</tr>
</thead>
<tbody>
<tr class="ship_bill">
<td>
12/12/17
</td>
<td>
<input id="purpose" type="text" name="purpose" required>
</td>
<td>
<input id="amount" name="amount" type="text"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" required>
</td>
<td>
<input id="quantity" name="quantity" required="required" type="number" min="0" value="0">
</td>
<td>
<strong><i><span class="multTotal">0.00</span></i></strong>
</td>
<td>
</td>
</tr>
</tbody>
</table>
<table class="table table-bordered">
<tbody>
<tr>
<td width="50%"><strong><i>Bill Amount:</i></strong></td>
<td><strong><i><span id="grandTotal">0.00</span></i></strong></td>
</tr>
</tbody>
</table>
Here is my jQuery codes:
var i=1;
$('#addBillingRow').click(function(){
i++;
$('#dynamic_field_shipping').append('<tr class="ship_bill" id="row'+i+'"><td></td><td><input id="purpose" type="text" name="purpose" required></td><td><input id="amount" name="amount" type="text" required></td><td><input id="quantity" name="quantity" required="required" type="number" min="0" value="0"></td><td><strong><i><span class="multTotal">0.00</span></i></strong></td><td>X</td></tr>');
});
$(document).on('click', '.btn_remove', function(e){
e.preventDefault();
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
function multInputs() {
var mult = 0;
// for each row:
$("tr.ship_bill").each(function () {
// get the values from this row:
var $amount = $('#amount', this).val();
var $quantity = $('#quantity', this).val();
var $total = ($amount * 1) * ($quantity * 1)
$('.multTotal',this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
$(".ship_bill input").change(multInputs);
If you want you can check the live code here:
https://jsfiddle.net/wasid/3xkcLdss/1/
besides I also wanted to use this code in jquery append() for allowing only numbers in input fields. but could not use it either.
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
Try this
$("tbody").on('change', '.ship_bill input', multInputs);

How to calculate total sum of checkbox values depend on quantity in textbox

I have the following table
<table>
<tr style="background-color: silver;">
<th>Check it</th>
<th>Estimate item</th>
<th>Quantity</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="checkbox" value="450" /></td>
<td>Remove Tile</td>
<td><input type="text" value="1"></td>
<td>$450</td>
</tr>
<tr>
<td><input type="checkbox" value="550" /></td>
<td>Remove Tub</td>
<td><input type="text" value="1"></td>
<td>$550</td>
</tr>
<p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>
Table example
I found how to calculate the sum of checkboxes values:
<script>
$(document).ready(function () {
var $inputs = $('input[type="checkbox"]')
$inputs.on('change', function () {
var sum = 0;
$inputs.each(function() {
if(this.checked)
sum += parseInt(this.value);
});
$("#price").val(sum);
});
});
</script>
The question is:
If user will update the quantity in textbox, i need to update the total.
I want it to work in two ways: quantity changed before or after checkbox has been checked.
So the value in "Cost" column is equal to checkbox value. I do not want to modify "Cost" column. I need total to be shown at the bottom of the table in "textbox with id="price" textbox.
Case:
User checked the first checkbox #price should be updated with 450.
User checked the second checkbox #price should benow 1000.
User changed the quantity to 2 in the row with the first checkbox.Now #price should be updated to 1450
Thanks in advance!
To achieve this you should loop through the table body's row for that use the code as
$('table tbody tr').each(function()
{
//do something
});
and then find the checkbox in that row. You can check if the check box is checked by using $tr.find('input[type="checkbox"]').is(':checked') this code. It will find a check box in the row and it will check whether it is checked or not.
var $columns = $tr.find('td').next('td').next('td'); This code is used to retrieve the column Quantity.
We call the function calculateSum() to calculate the sum coast of checked rows in both textbox change event and checkbox change event.
$(document).ready(function() {
function calculateSum(){
var sumTotal=0;
$('table tbody tr').each(function() {
var $tr = $(this);
if ($tr.find('input[type="checkbox"]').is(':checked')) {
var $columns = $tr.find('td').next('td').next('td');
var $Qnty=parseInt($tr.find('input[type="text"]').val());
var $Cost=parseInt($columns.next('td').html().split('$')[1]);
sumTotal+=$Qnty*$Cost;
}
});
$("#price").val(sumTotal);
}
$('#sum').on('click', function() {
calculateSum();
});
$("input[type='text']").keyup(function() {
calculateSum();
});
$("input[type='checkbox']").change(function() {
calculateSum();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sum" type="button">Calculate</button><br/>
<table>
<tr style="background-color: silver;">
<th>Check it</th>
<th>Estimate item</th>
<th>Quantity</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="checkbox" name="chck" value="450" /></td>
<td>Remove Tile</td>
<td><input type="text" name="qnty" value="1"></td>
<td>$450</td>
</tr>
<tr>
<td><input type="checkbox" class="chck" value="550" /></td>
<td>Remove Tub</td>
<td><input type="text" name="qnty" value="1"></td>
<td>$550</td>
</tr>
</table>
<p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>
<div class="serve" id="service">
<form action="" id="roomform" onsubmit="return false">
<div class="order">
<fieldset>
<legend>Tell us where to clean:</legend>
<p>
<input value="30" type="checkbox" id="myCheck" class="sum" name="myCheck" oninput="x.value=parseInt(bedroom.value)*30.00"/>
<label for="sleeping" class="contain">Bedrooms (P30/room) </label>
<input type="number" id="a" class="room" value="1" min="1" max="20" onchange="calculateTotal()"/>
Total: P <span id="costPrice"> </span
</p>
<p>
<input value="20" type="checkbox" id="myCheck" class="sum" name="myCheck1" onclick="calculateTotal()" />
<label for="sitting" class="contain">Sitting room (P20/room)</label>
<input type="number" class="room" id="a" value="1" min="1" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
<input value="20" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Dining room (P20/room)</label>
<input type="number" class="room" id="a" value="1" min="1" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
Extra services:</p>
<p>
<input value="15" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Carpet Cleaning (P 15/room)</label>
<input type="number" class="room" id="a" value="0" min="0" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
<input value="3" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Window Cleaning (P 3/room)</label>
<input type="number" class="room" id="a" value="0" min="0" max="20" />
Total: P <output type="number" ></output>
</p>
<div class="grandPrice" >
Grand Total Price: P<span id="grandTotal">0</span>
</div>
</fieldset>
</div>
</form>
<script>
// When a checkbox is clicked
/*$('#order input[type=checkbox]').click(function() {
// Get user input and set initial variable for the total
inputBox = parseInt($('#a').val());
bedroomPrices = 0;
// If it's checked, add the current value to total
if($(this).prop('checked'))
{
thisValue = parseInt($(this).val());
bedroomPrices = bedroomPrices + thisValue;
}
// Output the total checkbox value multipled against user input
$('#costPrice').html(bedroomPrices * inputBox);
});*/
var checkbox = document.getElementsByClassName('sum'),
inputBox = document.getElementById('a'),
GrandTotal = document.getElementById('grandTotal');
//"(this.checked ? 1 : -1);" this sees if checkbox is checked or unchecked by adding or subtracting it (1 :-1)
//make sure that each checkbox total is added if its checked
for (var i=0; i < checkbox.length; i++) {
checkbox[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
grandTotal.innerHTML = parseFloat(grandTotal.innerHTML) + add
}
}
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="indent_list">
<table border="1">
<thead>
<tr>
<th>rate</th>
<th>quantity</th>
<th>coltotal</th>
</tr>
</thead>
<body>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="1"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="2"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="2"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
</body>
<tfoot>
<tr>
<th class="rateRow"></th>
<th class="quantityRow"></th>
</tr>
<tr>
<th colspan="2" class="totalRow"></th>
</tr>
</tfoot>
</table>
</div>
> button
<input type="checkbox" class="btn btn-info checkbox" onclick="calculateCheck()">
<input type="button" class="btn btn-info" onclick="calculate()" value="Calculate">
> script
<script>
function calculateCheck() {
var check = $('.checkbox').prop('checked');
if (check) {
calculate()
} else {
$('.rateRow').text('');
$('.quantityRow').text('');
$('.totalRow').text('');
}
}
function calculate() {
var rateRow = '';
var quantityRow = '';
var totalRow = '';
var rate = 0;
var quantity = 0;
var total = 0;
// alert(quantitycol);
$('tbody tr').each(function () {
var ratecol = $('td .rate', this).val();
var quantitycol = $('td .quantity', this).val();
var coltotal = ratecol * quantitycol;
$('td .coltolal', this).val(coltotal);
// alert(a);
rate += +$('td .rate', this).val();
quantity += +$('td .quantity', this).val();
total = rate * quantity;
});
rateRow += rate;
quantityRow += quantity;
totalRow = total;
$('.rateRow').text(rateRow);
$('.quantityRow').text(quantityRow);
$('.totalRow').text(totalRow);
}
</script>

I need to add together multiple inputs, which are read only totals of 2 other inputs

I am needing help in basically adding together the sum total inputs, to make them add together to create a final amount.
As you can see in the image above, there can be multiple inputs, and the person can add more with the click of the button, the code works so the quantity and the unit price add together, however I am after the subtotals adding together automatically to keep updating the gbp total.
<table>
<tr>
<td>
<input type="number" oninput="calculate(this)" id="qid1" data-quantity name="qamount" min="0" data-validation="number" class="qinput txt" value="{{Quantity}}" />
</td>
<td>
<input type="text" data-validation="length" data-validation-length="max100" class="dinput" value="{{Details}}" />
</td>
<td>
<input type="number" oninput="calculate(this)" id="uid1" data-unitprice name="uamount" min="0" data-validation="number" data-validation-allowing="float" class="uinput txt" value="{{UnitPrice}}" />
</td>
<td>
<input readonly id="subsubtotal" name="totalamount" class="sinput txt" value="{{Subtotal}}" />
</td>
</tr>
</table>
<div class="additembtton">
<button id="bttonitem">Add Invoice Item</button>
<input id="bttonitem1" type="submit" value="Save" />
<span class="gbptotal">GBP Total</span>
<span id="totalplus" class="totalsub">£0.00</span>
</div>
JS
//code that multiplies the quantity and unit price input boxes
function calculate(obj) {
var tr = obj.parentNode.parentNode;
var myBox1 = tr.cells[0].children[0].value;
var myBox2 = tr.cells[2].children[0].value;
var result = tr.cells[3].children[0];
var myResult = parseFloat(myBox1) * parseFloat(myBox2);
result.value = myResult.toFixed(2);
}
The javascript above is what works already, this multiplies both the quantity and unit price together, I am struggling with how I would do the same with the sub total, to add all the sub totals together (however many there may be), and display the final total in where the £0.00 is.
<input id="bttonitem1" type="submit" value="Save" onclick="gbpTotal()">
function gbpTotal(){
var total = 0;
var inputs = document.querySelectorAll('.sinput');
inputs.forEach(function(e){
total += parseFloat(e.value);
});
document.querySelector('#totalplus').textContent = total;
};
You might want to trigger the function anytime they click out of an input instead of on the save
You'll need to query for all the inputs that are from the same column when it's time to total them up. This is best achieved by ensuring that the inputs in each column belong to the same CSS class. This way, it doesn't matter how many rows you wind up with and you won't have to worry about rows or cells, just inputs that belong to the same class.
So, here's an example that shows how to get the total of the total column, but the same approach would be used for any other columns.
var totals = document.querySelectorAll(".total");
var output = document.getElementById("total");
var btn = document.querySelector("button");
btn.addEventListener("click", function(){
var tot = null;
// Convert the node list of inputs that hold totals into an array and loop through that array
Array.prototype.slice.call(totals).forEach(function(element){
// Get the sum of the values
tot += parseFloat(element.value);
});
// Display the output
output.textContent = tot;
});
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="name"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="qty"></td>
<td><input type="text" class="total"></td>
</tr>
<tr>
<td><input type="text" class="name"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="qty"></td>
<td><input type="text" class="total"></td>
</tr>
<tr>
<td><input type="text" class="name"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="qty"></td>
<td><input type="text" class="total"></td>
</tr>
</tbody>
</table>
<div id="total"></div>
<button>Get Totals</button>

Dynamically add/remove rows from html table

I am working on a table that can be modified by pressing "Delete" buttons in each row and "Insert row" to add a new one at the end:
So far by now my code is:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteRow(id,row) {
document.getElementById(id).deleteRow(row);
}
function insRow(id) {
var filas = document.getElementById("myTable").rows.length;
var x = document.getElementById(id).insertRow(filas);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML = '<input type="text" id="fname">';
z.innerHTML ='<button id="btn" name="btn" > Delete</button>';
}
</script>
</head>
<body>
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',0)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',1)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',2)"></td>
</tr>
</table>
<p>
<input type="button" onclick="insRow('myTable')" value="Insert row">
</p>
</body>
</html>
But i cannot attach the function onclick="deleteRow('myTable',0)" on
z.innerHTML ='<button id="btn" name="btn"> Delete</button>'
¿Is there something else i need to declare in order to make that button work when clicked?
Thanks for your answers
First off, IDs must be unique, so why not use classes here instead?
Second, if you're using jQuery, then use jQuery.
Third, you need to use event delegation when dynamically adding elements, so try the following:
$('#myTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
$('#myTable').append('<tr><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" style="border: 1px solid black">
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</table>
<p>
<input type="button" value="Insert row">
</p>
On each DeleteRow(tableId,Index) function you are passing table id and static index that's why document.getElementById("mytable").deleteRow(Index) first find table node then find no of tr element as children and assigns the index to tr element start from 0 and delete the matching index tr element.
Whenever you delete first row then it will matches the 0 index from 3 elements and deletes the first row. Now there are 2 tr left with index 0 and 1 dynamically assign by table but you trying to match with 1 and 2.
for deleting second row it will delete tr with index 1 (third tr) not the second tr.
for deleting third row actual index is 0 (after deleting 2 rows) and you are passing 1 because of this reason it wont find the matching index.
Here is Simple javascript soltution.
<script>
function delRow(currElement) {
var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(parentRowIndex);
}
</script>
and html,
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
</table>
here is jsfiddle exmple
Click Here
Say you have the following table:
<table id="myTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="firstName" /></td>
<td><input type="text" name="lastName" /></td>
<td> <input type="text" name="email" /></td>
</tr>
</tbody>
<p>
<label>Insert</label>
<input type="number" value="1" id="numberOfRowsToInsert">
<input type="button" value="Insert row" id="insert-line-button">
</p>
</table>
The following jquery code will generate x number of rows entered by the user and append them to the bottom of the table with the ability to delete them if needed:
$('#insert-line-button').on("click", function(){
var noOfRows = $('#numberOfRowsToInsert').val();
for(var i = 0; i < noOfRows; i++){
$('#myTable').append("<tr>" +
"<td><input type='text' name='firstName' /></td>" +
"<td><input type='text' name='lastName' /></td>" +
"<td> <input type='text' name='email' /></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
}
});
And the following jquery code will remove the rows when clicked on the 'Delete' button:
$("#myTable").on('click', 'input[id="deleteRowButton"]', function(event) {
$(this).parent().parent().remove();
});
Go through below code:
You can see that this is the most basic way to create dynamic table. You can use this approach and can try yourself to remove rows from the existing table. I have not used any pluggin/ jquery. You can just copy this code and save as an html file to see how this code is working. Go head! Good luck.
<html>
<script>
function CreateTableAndRows(){
var mybody = document.getElementsByTagName("body")[0];
var newTable = document.createElement("table");
var newTableHead = document.createElement("thead");
var headRow = document.createElement("tr");
var headHead1 = document.createElement("th");
var headRowCellValue = document.createTextNode("Device Name");
headHead1.appendChild(headRowCellValue);
var headHead2 = document.createElement("th");
headRowCellValue = document.createTextNode("Start Timing");
headHead2.appendChild(headRowCellValue);
var headHead3 = document.createElement("th");
headRowCellValue = document.createTextNode("End Timing");
headHead3.appendChild(headRowCellValue);
var headHead4 = document.createElement("th");
headRowCellValue = document.createTextNode("Duration");
headHead4.appendChild(headRowCellValue);
headRow.appendChild(headHead1);
headRow.appendChild(headHead2);
headRow.appendChild(headHead3);
headRow.appendChild(headHead4);
newTableHead.appendChild(headRow);
newTable.appendChild(newTableHead);
var newTableBody = document.createElement("tbody");
for(var rowCount=0;rowCount<5;rowCount++)
{
var newTableRow = document.createElement("tr");
for(var cellCount=0; cellCount<4; cellCount++)
{
var newTableRowCell = document.createElement("td");
var cellValue = document.createTextNode("cell is row"+rowCount+", coumn "+cellCount);
newTableRowCell.appendChild(cellValue);
newTableRow.appendChild(newTableRowCell);
}
newTableBody.appendChild(newTableRow);
}
newTable.appendChild(newTableBody);
newTable.setAttribute("border","2");
mybody.appendChild(newTable);
}
</script>
</head>
<body>
<input type="submit" onclick="CreateTableAndRows();">
</body>
</html>

how to assign names to new table columns cells dynamically

At the moment ,this code can create new columns dynamically.I would like to be able to give a unique name to all cells belonging to the mother column.NB:the mother column is the tallest of them all with three columns always.Any thing with less columns is a child.
SO all the cells and the contents in the first group must have a unique name identifer like say name="Bx_1name" to identify them from the next mother's contents(BX_2name);
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
}
item.appendChild(td);
});
}
</script>
Javascript is wellcome too.the functionality must not be changed.it must be just like this;
jsfiddle
Try this if it fits what you need.
JSFIDDLE
var counter =0;
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME['+counter+']" value="BX_NAME['+counter+']"/>';
counter++;
}
item.appendChild(td);
});
}
i used a global counter to increment each time a cell is made.
this is just a hint you can implement this as you want to achieve. First assign same class name for all your input fields
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text"/>
</td>
</tr>
</tbody>
</table>
then assign diffrent id's using jquery like following
<script type="text/javascript">
$(document).ready(function (event) {
var IDCount = 1;
$('.text').each(function () {
$(this).attr('id', IDCount);
IDCount++;
});
</script>
Hope this will help

Categories

Resources