how to fix this issue..? - javascript

This is my complete code.I have used "for" to copy the table n-times.But A function "copy(Selector)" runs only at 1st table and not working in subsequent copied tables.Am a beginner and help me out with solution or alter the code.
And This is my fiddle https://jsfiddle.net/3shjhu98/3/
<!Doctype HTML>
<html>
<head>
<style>
table {
border-collapse: collapse
}
td {
border: 1px solid black;
height: 100%;
}
p001 {
border: none;
}
table {
counter-reset: section;
}
.count:before {
counter-increment: section;
content: counter(section);
}
</style>
<script type="text/javascript">
var num, i, c;
j = 1;
function cloneRow() {
num = document.getElementById("copying number").value;
for (i = 0; i < num - 1; i++) {
var row = document.getElementById("rowToClone");
var table = document.getElementById("tableToModify");
var clone = row.cloneNode(true);
clone.id = "newID";
table.appendChild(clone);
document.getElementById("Name1").value = "";
document.getElementById("Name2").value = "";
document.getElementById("Name3").value = "";
document.getElementById("Name4").value = "";
}
function createRow() {
var row = document.createElement('tr');
var col = document.createElement('td');
var col2 = document.createElement('td');
row.appendChild(col);
row.appendChild(col2);
var table = document.getElementById("tableToModify");
table.appendChild(row);
}
}
</script>
<script>
function copy(selector) {
var text1 = document.getElementById(selector + "1").value;
document.getElementById(selector + "2").value = text1;
var text2 = document.getElementById(selector + "3").value;
document.getElementById(selector + "4").value = text2;
}
</script>
<body>
<form>
<h4>Enter the number of times to be copied</h4>
<input type="text" id="copying number" placeholder="Enter Here">
<input type="reset" value="clear">
</form>
<br>
<br>
<input type="submit" value="Copy row" onclick="cloneRow()">
<br><br>
<table width="100%" id="tableToModify">
<tbody id="rowToClone">
<tr>
<td colspan="5" style="border:2px solid black;height:50px;text-align:center;">header
</tr>
<tr>
<td style="height:25px;width:11%;text-align:center;" class="count">Name</td>
<td colspan="3" style="width:11%;height:100px;text-align:center;">Age</td>
<td style="width:11%;text-align:center;">Gender</td>
</tr>
<tr>
<td rowspan="3" style="height:100px;">
<pre>Name <input type="text" name="Emp name" placeholder="enter your name" id="Name1"/><br>
ID <input type="id" name="Emp Id" placeholder="enter id" id="Name3" > </pre>
</td>
<td></td>
<td></td>
<td></td>
<td rowspan="3">
<pre>
<input type="radio" name="Gender" value="male">MALE</input>
<input type="radio" name="Gender" value="female">FEMALE</input> <br> <input type="radio" name="Gender" value="other">OTHER</input>
</pre>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr id="p01">
<td></td>
<td colspan="4" style="height:100px"></td>
</tr>
<tr>
<td colspan="5" style="height:50px;text-align:center;">
footer</td>
</tr>
<tr id="p001">
<td colspan="10" style="border:1px solid #ffffff;height:150px;"><input type="button" value="Get data" onclick="copy('Name');" />
<pre><label for="text"> Name : <input type="text" id="Name2"></label>
<label for="text"> ID : <input type="id" id="Name4"></label> </pre>
</tbody>
</table>
</body>
</head>
</html>

Related

my updatevalue function is not working when I click on remove butt

I dont know why the sum is not get update when I click on remove button after adding some value in input because when I input some value, it updates sum but when I remove, value becomes zero cause of remove_item function but doesnt update the sum. thank you so much for giving some time to my problem in advance.
function updatevalue(item, value, data) {
var td = item.parentNode.nextElementSibling;
var div = item.parentNode.parentNode.parentNode.parentNode.parentNode;
var onupdate = 0;
if (value) {
onupdate = data * value;
} else if (value === 0) {
onupdate = data * 0;
} else {
onupdate = data * 0;
}
td.innerHTML = onupdate;
var totalValues = document.querySelectorAll(".int-input");
var total = 0;
totalValues.forEach((k) => {
total += parseInt(k.innerHTML);
});
div.querySelector('.total').innerHTML = total
}
function add_item(item, next) {
item.parentNode.style.display = "none";
next.style.display = "block";
item.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.firstChild.value = '';
item.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.firstChild.disabled = false;
}
function remove_item(item, prev) {
item.parentNode.nextSibling.nextSibling.firstChild.disabled = true;
item.parentNode.nextSibling.nextSibling.firstChild.value = '0';
item.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.innerHTML = '0';
item.parentNode.style.display = "none";
prev.style.display = "block";
}
td {
border: 1px solid black;
text-align: center;
padding: 4px;
}
<div>
<h2>Div1</h2>
<table>
<th>Select</th>
<th>Intake</th>
<th>Total</th>
<tr>
<td><input id="btn" type="button" value="Add" name="{{a.Food}}" onclick="add_item(this, this.parentNode.nextSibling.nextSibling)"></td>
<td style="display: none;text-align: center;"><input id="btn" type="button" name="{{a.Food}}" value="Remove" onclick="remove_item(this,this.parentNode.previousElementSibling)"></td>
<td><input type="Number" name="some" id="{{a.Food}}" value="0" oninput="updatevalue(this,this.value,9)" disabled></td>
<td class="int-input">0</td>
</tr>
<tr>
<td>the sum of this div table </td>
<td class="total">0</td>
<td>sum</td>
</tr>
</table>
</div>
<div>
<h2>div2</h2>
<table>
<th>Select</th>
<th>Intake</th>
<th>Total</th>
<tr>
<td><input id="btn" type="button" value="Add" name="{{a.Food}}" onclick="add_item(this, this.parentNode.nextSibling.nextSibling)"></td>
<td style="display: none;text-align: center;"><input id="btn" type="button" name="{{a.Food}}" value="Remove" onclick="remove_item(this,this.parentNode.previousElementSibling)"></td>
<td><input type="Number" name="some" id="{{a.Food}}" value="0" oninput="updatevalue(this,this.value,9)" disabled></td>
<td class="int-input">0</td>
</tr>
<tr>
<td>the sum of this div table </td>
<td class="total">0</td>
<td>sum</td>
</tr>
</table>
</div>
Note: It's not a good practice to stack .nextSibling your way in order to select another element. Imagine having table with many columns, you would not want to use .nextSibling multiple times until you reach the target element.
If your <td> has id/class, you can use .querySelector() to select elements with specified selectors. I've modified your code, see sample snippet below:
//https://stackoverflow.com/questions/68965719/my-updatevalue-function-is-not-working-when-i-click-on-remove-butt/68966136
function updatevalue(item, value, data) {
var td = item.parentNode.nextElementSibling;
var div = item.parentNode.parentNode.parentNode.parentNode.parentNode;
var onupdate = 0;
if (value) {
onupdate = data * value;
} else if (value === 0) {
onupdate = data * 0;
} else {
onupdate = data * 0;
}
td.innerHTML = onupdate;
var totalValues = div.querySelectorAll(".int-input");
var total = 0;
totalValues.forEach((k) => {
total += parseInt(k.innerHTML);
});
div.querySelector('.total').innerHTML = total
}
function add_item(item) {
var tr = item.parentElement.parentElement;
var add = tr.querySelector('.addtd');
add.style.display = "none";
var remove = tr.querySelector('.removetd');
remove.style.display = "block";
var input = item.parentElement.parentElement.querySelector('.intake');
input.value = "";
input.disabled = false;
}
function remove_item(item,data) {
var tr = item.parentElement.parentElement;
var table = item.parentElement.parentElement.parentElement.parentElement;
var add = tr.querySelector('.addtd');
add.style.display = "block";
var remove = tr.querySelector('.removetd');
remove.style.display = "none";
var input = tr.querySelector('.intake');
input.value = "0";
input.disabled = true;
var total = tr.querySelector('.int-input');
total.innerHTML= "0";
// Loop through table to get sum
var sumvalue = 0;
var subtotal = table.querySelectorAll('.int-input');
subtotal.forEach((k) => {
sumvalue += parseInt(k.innerHTML);
});
var sum = table.querySelector('.total');
sum.innerHTML= sumvalue;
}
td {
border: 1px solid black;
text-align: center;
padding: 4px;
}
<div>
<h2>Div1</h2>
<table>
<th>Select</th>
<th>Intake</th>
<th>Total</th>
<tr>
<td class="addtd"><input id="btn" type="button" value="Add" name="{{a.Food}}" onclick="add_item(this)"></td>
<td style="display: none;text-align: center;" class="removetd"><input id="btn" type="button" name="{{a.Food}}" value="Remove" onclick="remove_item(this,this.parentNode.previousElementSibling)"></td>
<td><input type="Number" name="some" class="intake" id="{{a.Food}}" value="0" oninput="updatevalue(this,this.value,9)" disabled></td>
<td class="int-input">0</td>
</tr>
<tr>
<td class="addtd"><input id="btn" type="button" value="Add" name="{{a.Food}}" onclick="add_item(this)"></td>
<td style="display: none;text-align: center;" class="removetd"><input id="btn" type="button" name="{{a.Food}}" value="Remove" onclick="remove_item(this)"></td>
<td><input type="Number" name="some" class="intake" id="{{a.Food}}" value="0" oninput="updatevalue(this,this.value,9)" disabled></td>
<td class="int-input">0</td>
</tr>
<tr>
<td>the sum of this div table </td>
<td class="total">0</td>
<td>sum</td>
</tr>
</table>
</div>
<div>
<h2>div2</h2>
<table>
<th>Select</th>
<th>Intake</th>
<th>Total</th>
<tr>
<td class="addtd"><input id="btn" type="button" value="Add" name="{{a.Food}}" onclick="add_item(this)"></td>
<td style="display: none;text-align: center;" class="removetd"><input id="btn" type="button" name="{{a.Food}}" value="Remove" onclick="remove_item(this)"></td>
<td><input type="Number" name="some" class="intake" id="{{a.Food}}" value="0" oninput="updatevalue(this,this.value,9)" disabled></td>
<td class="int-input">0</td>
</tr>
<tr>
<td class="addtd"><input id="btn" type="button" value="Add" name="{{a.Food}}" onclick="add_item(this)"></td>
<td style="display: none;text-align: center;" class="removetd"><input id="btn" type="button" name="{{a.Food}}" value="Remove" onclick="remove_item(this)"></td>
<td><input type="Number" name="some" class="intake" id="{{a.Food}}" value="0" oninput="updatevalue(this,this.value,9)" disabled></td>
<td class="int-input">0</td>
</tr>
<tr>
<td>the sum of this div table </td>
<td class="total">0</td>
<td>sum</td>
</tr>
</table>
</div>

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 add a new row to table and change it's color?

I have to make a table in which I can dynamically add a new row. A user has to input first name, last name, age, etc. and choose a group. Depending on the user's group choice, a row with "friend" should have a particular style (for example green background color), with "family" pink background color, etc. So far I have added a new row.
How can I change the row style?
function newTableRow() {
var newRow = document.createElement("tr");
var newFirst = document.createElement("td");
var newLast = document.createElement("td");
var newEmail = document.createElement("td");
var newAge = document.createElement("td");
var newDate = document.createElement("td");
var newGender = document.createElement("td");
var newGroup = document.createElement("td");
var table = document.getElementById("tab");
table.appendChild(newRow);
newRow.appendChild(newFirst);
newRow.appendChild(newLast);
newRow.appendChild(newEmail);
newRow.appendChild(newAge);
newRow.appendChild(newDate);
newRow.appendChild(newGender);
newRow.appendChild(newGroup);
newFirst.innerHTML = document.getElementById("first").value;
newLast.innerHTML = document.getElementById("last").value;
newEmail.innerHTML = document.getElementById("email").value;
newAge.innerHTML = document.getElementById("age").value;
newDate.innerHTML = document.getElementById("date").value;
newGroup.innerHTML = document.getElementById("group").value;
newGender.innerHTML = document.getElementById("gender").value;
if (document.getElementById("group").value == "family")
document.getElementById(newRow).className = "style1";
if (document.getElementById("group").value == "friend")
document.getElementById(newRow).className = "style2";
if (document.getElementById("group").value == "work")
document.getElementById(newRow).className = "style3";
}
#container {
text-align: center;
margin-left: auto;
margin-right: auto;
}
table,
th,
td {
border: solid black 1px;
border-collapse: collapse;
padding: 20px;
}
.style1 {
background-color: pink;
}
.style2 {
background-color: green;
}
.style3 {
background-color: blue;
}
<div id="container">
<div id="content">
<table id="tab">
<tr>
<th> First Name </th>
<th> Last name </th>
<th> Email </th>
<th> Age </th>
<th> Date of birth</th>
<th> Gender</th>
<th> Group</th>
</tr>
<tr id="row">
<td id="first1"><input type="text" id="first"></td>
<td id="last1"><input type="text" id="last"></td>
<td id="emal1"><input type="email" id="email"></td>
<td id="age1"><input type="number" id="age"></td>
<td id="date1"><input type="date" id="date"></td>
<td id="gender1">
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="male">Male<br>
</td>
<td id="group1">
<select id="group">
<option value="family">family</option>
<option value="friend">friend</option>
<option value="work">work</option>
</select>
</td>
</tr>
</table>
<button onclick="newTableRow()">Add</button>
</div>
</div>
If you looked the console of the dev tools, you would see that you have some syntax errors in your code. I fixed then, compare your code with mine to see.
Propably, the code below is working as you expect.
#container
{
text-align:center;
margin-left:auto;
margin-right:auto;
}
table, th,td
{
border: solid black 1px;
border-collapse: collapse;
padding:20px;
}
.style1
{
background-color:pink;
}
.style2
{
background-color:green;
}
.style3
{
background-color:blue;
}
<! DOCTYPE html>
<html>
<head>
</head>
<link rel="stylesheet" href="style.css">
<body>
<div id="container">
<div id="content" >
<table id="tab">
<tr>
<th> First Name </th>
<th> Last name </th>
<th> Email </th>
<th> Age </th>
<th> Date of birth</th>
<th> Gender</th>
<th> Group</th>
</tr>
<tr id ="row">
<td id= "first1"> <input type="text" id="first"> </td>
<td id="last1"> <input type="text" id="last"> </td>
<td id="emal1"> <input type="email" id="email"> </td>
<td id="age1"> <input type="number" id="age"> </td>
<td id="date1"> <input type="date" id="date"> </td>
<td id="gender1"> <input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="male">Male <br> </td>
<td id="group1" >
<select id="group">
<option value="family">family</option>
<option value="friend">friend</option>
<option value="work">work</option>
</select>
</td>
</tr>
</table>
<button onclick="newTableRow()">Add</button>
</div>
</div>
<script>
function newTableRow()
{
var newRow= document.createElement("tr");
var newFirst= document.createElement("td");
var newLast= document.createElement("td");
var newEmail= document.createElement("td");
var newAge= document.createElement("td");
var newDate= document.createElement("td");
var newGender= document.createElement("td");
var newGroup= document.createElement("td");
var table= document.getElementById("tab");
table.appendChild(newRow);
newRow.appendChild(newFirst);
newRow.appendChild(newLast);
newRow.appendChild(newEmail);
newRow.appendChild(newAge);
newRow.appendChild(newDate);
newRow.appendChild(newGender);
newRow.appendChild(newGroup);
newFirst.innerHTML=document.getElementById("first").value;
newLast.innerHTML=document.getElementById("last").value;
newEmail.innerHTML=document.getElementById("email").value;
newAge.innerHTML=document.getElementById("age").value;
newDate.innerHTML=document.getElementById("date").value;
newGroup.innerHTML=document.getElementById("group").value;
newGender.innerHTML=document.getElementById("gender1").value;
if(document.getElementById("group").value=="family")
newRow.className = "style1";
if(document.getElementById("group").value=="friend")
newRow.className = "style2";
if(document.getElementById("group").value=="work")
newRow.className = "style3";
}
</script>
</body>
</html>

How to generate table tr based on a total number

i wrote the blow code to generate tr for my table based on a total count .
there is a input type text that contains a number and i want to generatge tr for my table according to that number
but it is not working .
here is my snippet :
function findTotal(){
var table = $("#travells");
var rowNum = parseInt($("#total").val(), 10);
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
(i+1),
"</td>",
'<td><input type="name" placeholder="text goes here..."></td>',
'<td><input type="name" placeholder="text goes here..."></td>',
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="findTotal()">
<input type="text" value="8" id="total"/>
<table id="travells">
<thead>
<tr class="travelcounting">
<th>name</th>
<th>gender</th>
<th>country</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id="Name" readonly/></td>
<td class="columns"><input type="text" id="gender" readonly/></td>
<td class="columns"><input type="text" id="country" readonly/></td>
</tr>
</tbody>
</table>
</body>
$( document ).ready(function() {
var table = $("#travells");
var rowNum = parseInt($("#total").val(), 10);
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
(i+1),
"</td>",
'<td><input type="name" placeholder="text goes here..."></td>',
'<td><input type="name" placeholder="text goes here..."></td>',
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="hidden" value="8" id="total"/>
<table id="travells">
<thead>
<tr class="travelcounting">
<th>name</th>
<th>gender</th>
<th>country</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id="Name" readonly/></td>
<td class="columns"><input type="text" id="gender" readonly/></td>
<td class="columns"><input type="text" id="country" readonly/></td>
</tr>
</tbody>
</table>
When constructing these kind of strings, the new template literals from ES6 are a good fit. See here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
function findTotal(){
var body = document.getElementsByTagName("tbody")[0];
var rowNum = parseInt(document.getElementById("total").value, 10);
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += `<tr>
<td>
${(i + 1)}
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>`;
};
body.innerHTML = resultHtml;
};
<body onload="findTotal()">
<input type="text" value="8" id="total"/>
<table id="travells">
<thead>
<tr class="travelcounting">
<th>name</th>
<th>gender</th>
<th>country</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id="Name" readonly/></td>
<td class="columns"><input type="text" id="gender" readonly/></td>
<td class="columns"><input type="text" id="country" readonly/></td>
</tr>
</tbody>
</table>
</body>
$("#RowC").on("click",function(){
var TRCnt=$("tbody >tr").length;
for(var i=TRCnt;i< (parseInt($("#RowNum").val())+TRCnt);i++){
let tr=$("<tr/>");
let inputName=$("<input/>",{type:"text",name:"name",placeholder:"name",value:i+1});
let inputGender=$("<input/>",{type:"text",name:"gender",placeholder:"gender"});
let inputCountry=$("<input/>",{type:"text",name:"country",placeholder:"country"});
tr.append($("<td/>").html(inputName));
tr.append($("<td/>").html(inputGender));
tr.append($("<td/>").html(inputCountry));
$("tbody").append(tr);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="RowNum" />
<input type="button" id="RowC" value="click" />
<hr>
<table>
<thead>
<tr>
<th>name</th>
<th>gender</th>
<th>country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This is the jquery code:
$("#submitButton").click(function() {
var table = $("#resultTable");
var rowNum = parseInt($("#table-row-num").val(), 10);
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
(i+1),
"</td>",
'<td><input type="name" placeholder="text goes here..."></td>',
'<td><input type="name" placeholder="text goes here..."></td>',
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
I wish you luck with implementation. :)
The Demo here: http://jsfiddle.net/fpd8dwtw/20/

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