Get data from table tr td and convert it to JSON - javascript

So far I have done this.
function deleteGroup(e) {
e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
}
var count;
function addGroup() {
var countPlus=count+1;
group = $('<table class="modified-table" id="mainTab' + count + '"> <tr><td align="left"><a style="color: green;font-weight:bold ">[ Group '+countPlus+']</a></td><td colspan="10"></td></tr><tr><td><input type="text" name="type[]" placeholder="Type Name" size="30"/></td> <td><input type="text" placeholder="No. Of Total Credit" name="totalCr[]" size="30"/></td>'+'<td><LABEL><span>Add Sub Category</span><input type="checkbox" name="Yes" value="Yes" onchange="addSubCategory(event)"></LABEL></td><td><input class="button" value="Delete" onclick="deleteGroup(this)" size="5"/> </td></tr></table>');
$('#group').append(group);
count++;
}
function addSubCategory(e) {
var tableId = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.id;
var i=0;
//alert(tableId);
if(tableId === "mainTable"){
i=0;
} else {
i= tableId.substr(tableId.length - 1);
}
row = $('<tr></tr><tr><td><input type="text" id="subType'+i+'" placeholder="Sub Type" name="subType['+i+'][]" size="20"></td><td><input type="text" placeholder="Total Credit" name="subCr['+i+'][]" size="20"></td><td><span class="" size="5" value=""/></td><td><input size="5" class="button" value="Delete" onclick="deleteGroup(this)" /></td></tr>'); //create row
$("#" + tableId).append(row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<TABLE>
<input type="button" class="button" value="Add Group" onclick="addGroup();" />
</TABLE>
<table class="modified-table" id="mainTab">
<tr>
<td align="left">
<a style="color: green;font-weight:bold ">[ Group 1]</a>
</td>
<td colspan="10"></td>
</tr>
<tr>
<td><input type="text" name="type[]" class="type-name" placeholder="Type Name" size="30"/></td>
<td><input type="text" name="totalCr[]"placeholder="No. Of Total Credit" size="30"/></td>
<td><LABEL>
<span>Add Sub Category</span>
<input type="checkbox" name="hasSub" onchange="addSubCategory(event)"></LABEL></td>
<td><input type="button" class="button" value="Delete" onclick="deleteGroup(this)" size="5"/>
</td>
</tr>
</table>
<table id="group">
</table>
</DIV>
It create dynamic data with unique id but again
The way I am doing this it is wrong may be.
coz Here group stays as the first row and
Subgroup stays as 2nd , third , 4th row and so on.
Here Add group button will create group and
Add subgroup button will add subgroup of that group.
I need the json data which can be separated by group /subgroup.
LIke :
Group 0 :
Subgroup 0;
Subgroup 1;
Subgroup 2;
Group 1 :
Subgroup 0;
Subgroup 1;
Subgroup 2;
..........
..........
Group 2 :
Subgroup 0;
Subgroup 1;
Subgroup 2;
----------
Any kind of help or suggestion is appreciated. Thanks in advance.

Related

implementing innerHTML to display output by using form

im planning to display my output thru innerHTML but the javascript cant seem to display my input just like i wanted. when user enter input into the form, i want to display the input by using innerHTML.
my attempt output is just in a normal list similar to something like this:
to students
output 1
output 2
output 3
to organizer
k1
k2
k5
<html>
<head>
<title>part b</title>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<form onsubmit="printChecked()">
<table>
<tr>
<th colspan="2">
activities
</th>
</tr>
<tr>
<td colspan="2">
list 3 kind of activities that you interest
</td>
</tr>
<tr>
<td>
1. to students
</td>
<td>
<textarea name = "pelajar1" rows = "4" cols = "110"></textarea>
<textarea name = "pelajar2" rows = "4" cols = "110"></textarea>
<textarea name = "pelajar3" rows = "4" cols = "110"></textarea>
</td>
</tr>
<tr>
<td>
TO ORGANIZER
</td>
<td>
<input type="checkbox" name="kl" value="communication">K1
<br>
<input type="checkbox" name="kl" value="problems">K2
<br>
<input type="checkbox" name="kl" value="teamwork">K3
<br>
<input type="checkbox" name="kl" value="info">K4
<br>
<input type="checkbox" name="kl" value="business">K5
<br>
<input type="checkbox" name="kl" value="ethics">K6
<br>
<input type="checkbox" name="kl" value="leadership">K7
<br>
</td>
</tr>
</table>
<br><br>
<input type="Submit" value="Submit">
</form>
<script>
function printChecked()
{
var pel1 = document.getElementsByName('pelajar1');
var pel2 = document.getElementsByName('pelajar2');
var pel3 = document.getElementsByName('pelajar3');
var items=document.getElementsByName('kl');
var selectedItems="";
for(var i=0; i<items.length; i++){
if(items[i].type=='checkbox' && items[i].checked==true)
selectedItems+=items[i].value+"\n";
}
document.getElementsByName("pelajar1").innerHTML = pel1;
document.getElementsByName("pelajar2").innerHTML = pel2;
document.getElementsByName("pelajar3").innerHTML = pel3;
document.getElementsByName("kl").innerHTML = items;
}
</script>
</body>
</html>
try this and see console
<html>
<head>
<title>part b</title>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<form>
<table>
<tr>
<th colspan="2">activities</th>
</tr>
<tr>
<html>
<head>
<title>part b</title>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<form onsubmit="printChecked">
<table>
<tr>
<th colspan="2">activities</th>
</tr>
<tr>
<td colspan="2">
list 3 kind of activities that you
interest
</td>
</tr>
<tr>
<td>1. to students</td>
<td>
<textarea
id="pelajar1"
rows="4"
cols="110"
></textarea>
<textarea
id="pelajar2"
rows="4"
cols="110"
></textarea>
<textarea
id="pelajar3"
rows="4"
cols="110"
></textarea>
</td>
</tr>
<tr>
<td>TO ORGANIZER</td>
<td>
<br />
<input
type="checkbox"
id="k1"
value="communication"
/>K1
<input
type="checkbox"
id="k2"
value="problems"
/>K2
<br />
<input
type="checkbox"
id="k3"
value="teamwork"
/>K3
<br />
<input
type="checkbox"
id="k4"
value="info"
/>K4
<br />
<input
type="checkbox"
id="k5"
value="business"
/>K5
<br />
<input
type="checkbox"
id="k6"
value="ethics"
/>K6
<br />
<input
type="checkbox"
id="k7"
value="leadership"
/>K7
<br />
</td>
</tr>
</table>
<br /><br />
<input
type="button"
onclick="printChecked()"
value="Submit"
/>
</form>
<div id="form"></div>
<script>
function printChecked() {
var pel1 =
document.getElementById("pelajar1");
var pel2 =
document.getElementById("pelajar2");
var pel3 =
document.getElementById("pelajar3");
var items = [];
for (let i = 0; i < 7; i++) {
var a = document.getElementById(
"k" + (i + 1),
);
a.checked ? items.push(a.value) : null;
}
console.log(
"1 : " +
pel1.value +
"\n2 :" +
pel2.value +
"\n3 :" +
pel3.value,
);
items.forEach((element) => {
console.log(element);
});
}
</script>
</body>
</html>
</tr>
</table>
</form>
</body>
</html>
Okay i am not so clear about what you want to achieve in here, i believe you want the form submit not to do submission and get the details in the function for some kind of computation , i use this as for a javascript approach for preventing default form submit
make use of a return function that returns false stating not to submit the form as in below example
if this satisfies your query, please refer=>
function printChecked() {
var pel1 = document.getElementsByName('pelajar1');
var pel2 = document.getElementsByName('pelajar2');
var pel3 = document.getElementsByName('pelajar3');
var items = document.getElementsByName('kl');
var selectedItems = "";
for (var i = 0; i < items.length; i++) {
if (items[i].type == 'checkbox' && items[i].checked == true)
selectedItems += items[i].value + "\n";
}
console.log("pel1-data=> "+pel1[0].value);
console.log("pel2-data=> "+pel2[0].value);
console.log("pel3-data=> "+pel3[0].value);
console.log("checkbox-data=> "+selectedItems);
return false;
}
table,
th,
td {
border: 1px solid black;
}
<form onsubmit="return printChecked()">
<table>
<tr>
<th colspan="2">
activities
</th>
</tr>
<tr>
<td colspan="2">
list 3 kind of activities that you interest
</td>
</tr>
<tr>
<td>
1. to students
</td>
<td>
<textarea name="pelajar1" rows="4" cols="110"></textarea>
<textarea name="pelajar2" rows="4" cols="110"></textarea>
<textarea name="pelajar3" rows="4" cols="110"></textarea>
</td>
</tr>
<tr>
<td>
TO ORGANIZER
</td>
<td>
<input type="checkbox" name="kl" value="communication">K1
<br>
<input type="checkbox" name="kl" value="problems">K2
<br>
<input type="checkbox" name="kl" value="teamwork">K3
<br>
<input type="checkbox" name="kl" value="info">K4
<br>
<input type="checkbox" name="kl" value="business">K5
<br>
<input type="checkbox" name="kl" value="ethics">K6
<br>
<input type="checkbox" name="kl" value="leadership">K7
<br>
</td>
</tr>
</table>
<br><br>
<input type="Submit" value="Submit">
</form>
you can see return for onsubmit of form which gets value from the function printChecked() -> see last return statement in function
Additional
for jquery inside the called function definition we can just add the received event's preventDefault function
$("form").submit(function(event){
event.preventDefault();
});
Edit-> prints data on the same page using innerHtml
function printChecked() {
var pel1 = document.getElementsByName('pelajar1');
var pel2 = document.getElementsByName('pelajar2');
var pel3 = document.getElementsByName('pelajar3');
var items = document.getElementsByName('kl');
var selectedItems = "";
for (var i = 0; i < items.length; i++) {
if (items[i].type == 'checkbox' && items[i].checked == true)
//selectedItems += items[i].value + "\n";
//add values as li elements
selectedItems += '<li>'+ items[i].value + '</li>';
}
//show list on submit
document.getElementById("toStudents").style.display = "block";
document.getElementById("toOrganizer").style.display = "block";
//add tostudents text area values in to list
document.getElementById("pelajar1").innerHTML=pel1[0].value;
document.getElementById("pelajar2").innerHTML=pel2[0].value;
document.getElementById("pelajar3").innerHTML=pel3[0].value;
//add toorganizer checkbox values in to list
document.getElementById("toOrganizer").innerHTML=selectedItems;
//just printing values in console
//console.log("pel1-data=> "+pel1[0].value);
//console.log("pel2-data=> "+pel2[0].value);
//console.log("pel3-data=> "+pel3[0].value);
//console.log("checkbox-data=> "+selectedItems);
return false;
}
table,
th,
td {
border: 1px solid black;
}
/*list is hidden at first*/
#toStudents,#toOrganizer{
display:none;
list-style:none;
}
<form onsubmit="return printChecked()">
<table>
<tr>
<th colspan="2">
activities
</th>
</tr>
<tr>
<td colspan="2">
list 3 kind of activities that you interest
</td>
</tr>
<tr>
<td>
1. to students
</td>
<td>
<textarea name="pelajar1" rows="4" cols="110"></textarea>
<textarea name="pelajar2" rows="4" cols="110"></textarea>
<textarea name="pelajar3" rows="4" cols="110"></textarea>
</td>
</tr>
<tr>
<td>
TO ORGANIZER
</td>
<td>
<input type="checkbox" name="kl" value="communication">K1
<br>
<input type="checkbox" name="kl" value="problems">K2
<br>
<input type="checkbox" name="kl" value="teamwork">K3
<br>
<input type="checkbox" name="kl" value="info">K4
<br>
<input type="checkbox" name="kl" value="business">K5
<br>
<input type="checkbox" name="kl" value="ethics">K6
<br>
<input type="checkbox" name="kl" value="leadership">K7
<br>
</td>
</tr>
</table>
<br><br>
<input type="Submit" value="Submit">
<h2>To Students</h2>
<ul id="toStudents">
<li id="pelajar1"></li>
<li id="pelajar2"></li>
<li id="pelajar3"></li>
</ul>
<h2>To Organizer</h2>
<ul id="toOrganizer">
</ul>
</form>
the issue you seem to be experiencing is from the page reloading on the form submit BEFORE the JS function is called. Based on your code, you are calling printChecked() onsubmit when the button is clicked.
To fix your issue, look into Stop form refreshing page on submit, which, among other things, would involve adding return false to your onsubmit call. Other solutions from the same page mention not using button type="submit", and instead focusing on using the type="button" with a separate call from there onclick.
Hopefully this helps!

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>

Get data from table row to Javascript

I have table . There are three columns : Name , Price and button "Make Order". I must get data from each row to my Javascript. Each input have id such as productName and productPrice .
Table code:
<table border="2px">
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<c:forEach items="${productList}" var="product" varStatus="status">
<tr>
<form>
<td> ${product.getProductName()}</td>
<input type="hidden" id="productName" name="productName" value=${product.getProductName()}>
<td>${product.getPrice()}</td>
<input type="hidden" id="productPrice" name="productPrice" value=${product.getPrice()}>
<td><input type="submit" onclick="makeOrder()" value="Make Order"></td>
</form>
</tr>
</c:forEach>
</table>
And my js:
<script type="text/javascript">
function makeOrder() {
var n=document.getElementById("productName").value;
var p=document.getElementById("productPrice").value;
alert("n="+n);
alert("p="+p);
//var win=window.open("/user/makeOrder?productName=" + n + "&productPrice=" + p);
}
But when I click on my button I always alert first row of my table .
How can I alert other row ?
Use a unique row id for each row and pass that id with makeOrder() function and then find child elements inside that row whose id is passed in function...
Here is working example....
function makeOrder(rowId)
{
var n=document.getElementById(rowId).childNodes[5].value;
var p=document.getElementById(rowId).childNodes[9].value;
alert("n="+n);
alert("p="+p);
//var win=window.open("/user/makeOrder?productName=" + n + "&productPrice=" + p);
}
<table border="2px">
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<tr id="row1">
<form>
<td>P1</td>
<input type="hidden" id="productName" name="productName" value="P1">
<td>$5</td>
<input type="hidden" id="productPrice" name="productPrice" value="5">
<td><input type="button" onclick="makeOrder('row1')" value="Make Order"></td>
</form>
</tr>
<tr id="row2">
<form>
<td>P2</td>
<input type="hidden" id="productName" name="productName" value="P2">
<td>$6</td>
<input type="hidden" id="productPrice" name="productPrice" value="6">
<td><input type="button" onclick="makeOrder('row2')" value="Make Order"></td>
</form>
</tr>
</table>
You could call a function that gives all inputs with name productName, see below.
var n=document.getElementsByName("productName").value;
var p=document.getElementsByName("productPrice").value;
for(var i = 0; i < n.length; i++) {
alert("row 1: " + n[i].value + p[i].value);
}
This should return all your rows. Each alert will show the data of 1 row.

hide and show text box on click of a tr and on button click print the same in a div

I am trying to show text box on the row clicked by hiding the labels of the clicked row and on button click the text box data should be printed on a "showresult" Div
My problem is am not able to hide and show the textbox i have gathered a script which change the color but am not sure how to hide and show the text box and print the data.
$(document).ready(function () {
$('tr').click(function () {
if(this.style.background == "" || this.style.background =="white") {
$(this).css('background', 'red');
}
else {
$(this).css('background', 'white');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" cellspacing="1" width="100%" id="table1">
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
<th>Column5</th>
</tr>
<tr>
<td><label>data1</label> <input type="text" value="1" /></td>
<td><label>data2</label> <input type="text" value="2" /></td>
<td><label>data3</label> <input type="text" value="3" /></td>
<td><label>data4</label> <input type="text" value="4" /></td>
<td><label>data5</label> <input type="text" value="5" /></td>
</tr>
<tr>
<td><label>data6</label> <input type="text" value="6" /></td>
<td><label>data7</label> <input type="text" value="7" /></td>
<td><label>data8</label> <input type="text" value="8" /></td>
<td><label>data9</label> <input type="text" value="9" /></td>
<td><label>data10</label> <input type="text" value="10" /></td>
</tr>
</table>
<input type="button" value="printdata"/>
<div id="showresult"></div>
Say i have two rows, The textbox will be hidden and the label will be
available as a display when a user click on a selected row the label
should be hidden and the text box should be visible and after that if
the user clicks on the button then the data or the clicked row textbox
value should be printed #showresult
Try utilizing .toggle() to display , not display label , input elements within tr clicked element ; create variable index corresponding to tr element clicked ; at click of #printdata , iterate
tr at index using .each() , create an object having property of label , value of input , set #showresult html to created object
$(document).ready(function() {
var index = null;
$("tr").click(function() {
$("input, label", this).toggle();
index = $(this).index("tr");
});
$("input[type=button]").click(function() {
var obj = {};
var elems = $("tr").eq(index).find("label, input");
elems.each(function(i, el) {
if ($(el).is("label")) {
obj[el.textContent] = elems[i + 1].value
}
});
$("#showresult").html("<pre>" + JSON.stringify(obj, null, 2) + "</pre>")
})
});
tr td input {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1" cellspacing="1" width="100%" id="table1">
<tbody>
<tr style="background:transparent">
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
<th>Column5</th>
</tr>
<tr>
<td>
<label>data1</label>
<input type="text" value="1" />
</td>
<td>
<label>data2</label>
<input type="text" value="2" />
</td>
<td>
<label>data3</label>
<input type="text" value="3" />
</td>
<td>
<label>data4</label>
<input type="text" value="4" />
</td>
<td>
<label>data5</label>
<input type="text" value="5" />
</td>
</tr>
<tr>
<td>
<label>data6</label>
<input type="text" value="6" />
</td>
<td>
<label>data7</label>
<input type="text" value="7" />
</td>
<td>
<label>data8</label>
<input type="text" value="8" />
</td>
<td>
<label>data9</label>
<input type="text" value="9" />
</td>
<td>
<label>data10</label>
<input type="text" value="10" />
</td>
</tr>
</tbody>
</table>
<input type="button" value="printdata" />
<div id="showresult"></div>

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>

Categories

Resources