How can I highlight the table column? - javascript

In my table I have STUDENTID, FULLNAME, SEX, COURSE & SUBJECT. I used combobox to search for all the 'Male' or 'Female' in my table. For example, I choose 'Male' I want all the Male column or cell will be highlighted with any colors. Only the 'SEX' column will be highlighted. How can I do it on javascript?
function searchForSex() {
var input, filter, table, tr, td, i;
input = document.getElementById("txtSearch");
filter = input.value.toUpperCase();
table = document.getElementById("tblStudent");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[2];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.backgroundColor = "red";
}
}
}
}
Search:
<select id="txtSearch"><br><br>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br><br>
<button onclick="searchForSex()">Search</button><br><br> ID:
<br>
<input type="text" id="txtProdName"><br><br> FULL Name:<br>
<input type="text" id="txtProdName"><br><br> SEX:
<br>
<select id="cboSex">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br><br> COURSE:
<br>
<input type="text" id="txtCourse"><br><br> SUBJECT:
<br>
<input type="text" id="txtSubject"><br><br>
<button onclick="insertValueTable()">Save</button>
<button>Cancel</button>
<br><br>
<table border="1px">
<th>ID</th>
<th>FULL NAME</th>
<th>SEX</th>
<th>COURSE</th>
<th>SUBJECT</th>
<tbody id="tblStudent">
</tbody>
</table>

You could do it like this for example.
And on another note: searchForSex is a pretty interesting function name.
function searchForSex() {
var input, filter, table, tr, i;
input = document.getElementById("txtSearch");
filter = input.value.toUpperCase();
table = document.getElementById("tblStudent");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
let tds = tr[i].getElementsByTagName("td");
let sextd = tds[2];
if (sextd) {
sextd.style.backgroundColor = ""; // Reset color when re-searching
if (sextd.innerHTML.toUpperCase() === filter){
sextd.style.backgroundColor = "green";
}
}
}
}
Search:
<select id="txtSearch"><br><br>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br><br>
<button onclick="searchForSex()">Search</button><br><br> ID:
<br>
<input type="text" id="txtProdName"><br><br> FULL Name:<br>
<input type="text" id="txtProdName"><br><br> SEX:
<br>
<select id="cboSex">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br><br> COURSE:
<br>
<input type="text" id="txtCourse"><br><br> SUBJECT:
<br>
<input type="text" id="txtSubject"><br><br>
<button onclick="insertValueTable()">Save</button>
<button>Cancel</button>
<br><br>
<table border="1px">
<th>ID</th>
<th>FULL NAME</th>
<th>SEX</th>
<th>COURSE</th>
<th>SUBJECT</th>
<tbody id="tblStudent">
<tr>
<td>1</td>
<td>Pat Johnsson</td>
<td>Male</td>
<td>Subject 1</td>
</tr>
<tr>
<td>2</td>
<td>Molly McGill</td>
<td>Female</td>
<td>Subject 2</td>
</tr>
</tbody>
</table>

Here's a much simpler solution:
var input;
var tableTD = document.body.querySelectorAll("#tblStudent td");
function searchForSex() {
input = document.body.querySelector("#txtSearch").value;
for (var tableCell of tableTD){
tableCell.style.backgroundColor = "transparent";
if(tableCell.innerHTML == input){
tableCell.style.backgroundColor = "red";
}
}
}

Related

How can I link a select with my tablehead?

I want to know how can I link my tableheads with a select ?
Here is a screen of how it looks
I just want to add a town in a column I've chosen before.
Here is my code :
function addRow() {
var table = document.getElementById("table");
var row= table.insertRow(-1);
var column1 = row.insertCell(0);
column1.innerHTML += document.getElementById("ville").value;
}
<h2>Test</h2>
<form method="post" action="">
<select id="select">
<option selected disabled>Choose one</option>
<option>Option A</option>
<option>Option B</option>
<option>Option C</option>
<option>Option D</option>
<option>Option E</option>
</select>
<input type="text" name="ville" id="ville" />
<input type="button" onclick="addRow();" value="Save"/>
</form>
<table id="table" style="margin: 30px; border-spacing: 20px;">
<thead>
<tr>
<th>Option A</th>
<th>Option B</th>
<th>Option C</th>
<th>Option D</th>
</tr>
</thead>
<tbody>
<tr>
<td>TEST</td>
</tr>
</tbody>
</table>
You need to have the select list provide you with the column number the new text needs to go in. Something like:
function addRow() {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var columnpicked = document.getElementById("select").value;
for (let i = 0; i <= columnpicked; i++) {
row.insertCell(0);
}
row.cells[columnpicked].innerHTML += document.getElementById("ville").value;
}
<h2>Test</h2>
<select id="select">
<option selected disabled>Choose one</option>
<option value=0>Option A</option>
<option value=1>Option B</option>
<option value=2>Option C</option>
<option value=3>Option D</option>
<option value=4>Option E</option>
</select>
<input type="text" name="ville" id="ville" />
<input type="button" onclick="addRow();" value="Save"/>
<table id="table" style="margin: 30px; border-spacing: 20px;">
<thead>
<tr>
<th>Option A</th>
<th>Option B</th>
<th>Option C</th>
<th>Option D</th>
<th>Option E</th>
</tr>
</thead>
<tbody>
<tr>
<td>TEST</td>
</tr>
</tbody>
</table>
Note that you only had four columns in your example - so, I've added an Option E column to match the select list items.
I will leave the other answer there in case we need to go back to it. From your comments, I think you need to do something like:
function addRow() {
// Get the tbody element - NOTE: an id has been added to that to make it easier to find
var table = document.getElementById("tablerows");
// Get the rows in the tbody element
var rows = table.getElementsByTagName("tr");
// If there are no rows, create one
if (rows.length == 0) {
tbody.insertRow();
}
// Get the first row
var row = rows[0];
// Get the column selected by the user
var selected = document.getElementById("select").value;
// Check if the row has enough td items to put the text into the selected column
if (row.cells.length - 1 < selected) {
// If it hasn't, create them
for (let i = 0; i < selected; i++) {
let td = document.createElement("td");
row.appendChild(td);
}
}
// Get the text to be inserted
var ville = document.getElementById("ville");
// Insert the text in the selected column
row.cells[selected].innerHTML = ville.value;
}
<h2>Test</h2>
<select id="select">
<option selected disabled>Choose one</option>
<option value=0>Option A</option>
<option value=1>Option B</option>
<option value=2>Option C</option>
<option value=3>Option D</option>
<option value=4>Option E</option>
</select>
<input type="text" name="ville" id="ville" />
<input type="button" onclick="addRow();" value="Save"/>
<table id="table" style="margin: 30px; border-spacing: 20px;">
<thead>
<tr>
<th>Option A</th>
<th>Option B</th>
<th>Option C</th>
<th>Option D</th>
<th>Option E</th>
</tr>
</thead>
<tbody id="tablerows">
<tr>
<td>TEST</td>
</tr>
</tbody>
</table>
I have added an id to the tbody tag as the header row is seen as part of the table's rows collection. Doing this means that we can target only the rows on the tbody.
OK - assuming we are ok for the users to enter text directly in a cell, try:
function addRow() {
var t = document.getElementById("datarows");
var rtemplate = document.getElementById("newrow");
var r = rtemplate.content.cloneNode(true);
t.appendChild(r);
}
table {border-collapse:collapse;}
td {height:23px; background-color:white; border:1px solid black; padding:5px; width:100px; vertical-align:top;}
th {border:1px solid black; padding:5px; width:100px;}
td:focus {background-color:lightgreen;}
<b>Click on a table cell to add/edit text</b><br>or click to add a new row <button id="newrowbutton" onclick="addRow();">Add new row</button>
<hr>
<table>
<thead id="headerrow">
<tr>
<th>Option A</th>
<th>Option B</th>
<th>Option C</th>
<th>Option D</th>
<th>Option E</th>
</tr>
</thead>
<tbody id="datarows">
<tr>
<td contenteditable></td>
<td contenteditable></td>
<td contenteditable></td>
<td contenteditable></td>
<td contenteditable></td>
</tr>
</tbody>
</table>
<template id="newrow">
<tr>
<td contenteditable></td>
<td contenteditable></td>
<td contenteditable></td>
<td contenteditable></td>
<td contenteditable></td>
</tr>
</template>

How to change Id of cloned row in below jQuery code

I'm trying to achieve the change of Id But the code what I have is only having the code to change the name of the element can anyone please help to change the id of the element in the below give jquery code
Thanks in Advance.
Html View-source code is as follows
<div style="width:700px; padding:5px; background-color:white;">
<form action="/" method="post">
<a id="addNew" href="#">+</a> <a id="remove" href="#">-</a>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>UserName</th>
<th>Password</th>
<th>Service line</th>
<th>Track</th>
<th>subtrack</th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="TemplateRow" style="border:1px solid black">
<td><input data-val="true" data-val-required="The Username field is required." id="z0__UserName" name="[0].UserName" type="text" value="Required" /></td>
<td><input data-val="true" data-val-required="The Password field is required." id="z0__Password" name="[0].Password" type="text" value="Required" /></td>
<td>
<select class="wrapper-dropdown Service_Line" id="z0__Service_Line" name="[0].Service_Line">
<option value="">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</td>
<td>
<select class="wrapper-dropdown Track" id="z0__Track" name="[0].Track">
<option value="">--Select--</option>
<option> </option>
</select>
</td>
<td>
<select class="wrapper-dropdown Sub_Track" id="z0__Sub_Track" name="[0].Sub_Track">
<option value="">--Select--</option>
<option> </option>
</select>
</td>
<td></td>
</tr>
</tbody>
</table>
<input type="submit" value="Save Bulk Data" />
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Iv10IHEfBVKvKHuuUa1dyFaBzngVKjKG3-va_WAZxz30jKahHLoMeCFM1qbmA9nPf01CYch9VobgyZOOv60VPsPJjlD4yUbH4F7TF0QrcJJTnMpj88n1Et9Ksa2i2y23CBEPqICCPoC18cdrY1Ral0" />
</form>
</div>
Jquery is as follows
$(document).ready(function () {
//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone(true);
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
// If you have another Type then replace with default value
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
});
});
I have tried by changing the attr(name) to attr(id) after changing like that its not changing the name but even not changing the ids too...
For more reference the Html code is as follows::
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>UserName</th>
<th>Password</th>
<th>Service line</th>
<th>Track</th>
<th>subtrack</th>
<th></th>
</tr>
</thead>
<tbody>
#if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr id="TemplateRow" style="border:1px solid black">
<td>#Html.TextBoxFor(a => a[j].UserName)</td>
<td>#Html.TextBoxFor(a => a[j].Password)</td>
<td>
#if (ViewBag.ServiceLineList != null)
{
#Html.DropDownListFor(a => a[j].Service_Line, ViewBag.ServiceLineList as SelectList, "--Select--", new { #class = "wrapper-dropdown Service_Line" })
}
</td>
<td>
#Html.DropDownListFor(a => a[j].Track, new SelectList(" "), "--Select--", new { #class = "wrapper-dropdown Track" })
</td>
<td>
#Html.DropDownListFor(a => a[j].Sub_Track, new SelectList(" "), "--Select--", new { #class = "wrapper-dropdown Sub_Track" })
</td>
<td>
#if (j > 0)
{
Remove
}
</td>
</tr>
j++;
}
}
</tbody>
</table>
To create a unique id, we can keep a count of the rows added in the jQuery, and append this to the base name (e.g. UserName) to create a unique name and id. You say there will only be one row in the HTML, so we can start the count for our new rows at 1.
Every time the "Add New" button is clicked, the steps are (numbers match the comment numbers):
Initialise our variable to start the count
generate a unique id for the row, e.g. TemplateRow-1: var newId = "TemplateRow-" + rowcount;
Clone the row and pass in the id: $trLast.clone(true).prop({ id: newId});
generate the name and id for each input: get the input name, remove the [n] to get the base name (e.g. UserName), and use this to create the new name (e.g. [1].UserName) and id (e.g. z1__UserName).
Working snippet: I show the new id using console.log so you can see what is being added:
$(document).ready(function() {
/* 1. Initialise our variable to keep count of the rows added */
var rowcount = 1;
//Add new row
$("#addNew").click(function(e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
// 2. Create the new id with the row count
var newId = "TemplateRow-" + rowcount;
// 3. clone the row with our new id
var $trNew = $trLast.clone(true).prop({ id: newId });
// 4. rename each input and give an id
$.each($trNew.find(':input'), function(i, val) {
oldName = $(this).attr('name');
inputParts = oldName.split(".");
// set the name and id with the base name and rowcount
$(this).attr('name', '[' + rowcount + '].'+inputParts[1]);
$(this).attr('id', 'z'+rowcount+'__'+inputParts[1]);
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
rowcount++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>UserName</th>
<th>Password</th>
<th>Service line</th>
<th>Track</th>
<th>subtrack</th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="TemplateRow" style="border:1px solid black">
<!-- <td><input type="text" name="username"></td>
<td><select name="serviceline"><option>1</option></select></td>
<td><input type="text" name="track"></td>
<td><input type="text" name="subtrack"></td> -->
<td><input data-val="true" data-val-required="The Username field is required." id="z0__UserName" name="[0].UserName" type="text" value="Required" /></td>
<td><input data-val="true" data-val-required="The Password field is required." id="z0__Password" name="[0].Password" type="text" value="Required" /></td>
<td>
<select class="wrapper-dropdown Service_Line" id="z0__Service_Line" name="[0].Service_Line">
<option value="">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</td>
<td>
<select class="wrapper-dropdown Track" id="z0__Track" name="[0].Track">
<option value="">--Select--</option>
<option> </option>
</select>
</td>
<td>
<select class="wrapper-dropdown Sub_Track" id="z0__Sub_Track" name="[0].Sub_Track">
<option value="">--Select--</option>
<option> </option>
</select>
</td>
<td></td>
</tr>
</tbody>
</table>
<button id="addNew">Add New</button>

Show values in the html table as json array on button click is not working as expected

User can enter values in some or all the rows present in the html table and click on the submit button. If a value is present in the row (if at least one column field value is entered) and the submit button is clicked, I want to get all the details as a json array.
Working sample demo : http://jsfiddle.net/Crw2C/173/
In the working demo above, when the user clicks on the convert button, the data from the html table is shown as a json array. I tried a similar implementation in my demo as shown in the code below but it is not working as expected.
My sample demo code which is not working as expected: http://plnkr.co/edit/FODEJ1BnhPLGHoH9kjO5?p=preview
Sample html code:
<table id="productTable" border="1">
<tr>
<th>Order ID</th>
<th>Product1</th>
<th>Description</th>
<th>Product2</th>
<th>Comments</th>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
.......
Sample js code:
$('#productTable th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
arrayItem[headers[index]] = $(item).html();
});
array.push(arrayItem);
});
Note: With my code above, the entire html element is retrieved and stored as json array but I only want the value. Any sample code would be appreciated as I tried to search and tried in different ways but was unable to succeed. The sample code I tried I also shared in the demo link above, which is not working. Thanks.
You are selecting the whole <td>...</td> instead of this select html input or select elements.
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index) {
arrayItem[headers[index]] = $(this).val();
});
array.push(arrayItem);
});
Check below snippet.
function populateSelect() {
var ids = [{"pid":"laptop","des":"laptop"},{"pid":"Mobile","des":"Mobile"},{"pid":"IPAD mini.","des":"IPAD mini."}]
var productDropdown1 = $(".product1");
var productDropdown2 = $(".product2");
$.each(ids, function(index,value) {
$("<option />").text(value.des).val(value.pid).appendTo(productDropdown1);
$("<option />").text(value.des).val(value.pid).appendTo(productDropdown2);
});
$("select").change(function() {
var row = $(this).closest("tr");
var product1_drop = $('.product1',row).val();
var product2_drop = $('.product2',row).val();
var descValue = $('input[name="description"]',row).val();
if( product1_drop && product2_drop)
validate(product1_drop,product2_drop, descValue);
});
$('input[name="description"]').on('input', function(e){
var row = $(this).closest("tr");
var product1_drop = $('.product1',row).val();
var product2_drop = $('.product2',row).val();
console.log("-inut -product1_drop----- " + product1_drop);
if( product1_drop && product2_drop)
validate(product1_drop,product2_drop, $(this).val());
});
}
function validate(prod1, prod2, desc){
if(desc && prod1 === prod2 ){
alert('Product1 and Product2 cannot have same value');
}
}
function submitData(){
alert("submit");
var array = [];
var headers = [];
$('#productTable th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index) {
arrayItem[headers[index]] = $(this).val();
});
array.push(arrayItem);
});
alert(JSON.stringify(array));
}
$(document).ready(function(){
populateSelect();
// $('#productTable tbody tr:gt(0) :input').prop('disabled',true)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="productTable" border="1">
<tr>
<th>Order ID</th>
<th>Product1</th>
<th>Description</th>
<th>Product2</th>
<th>Comments</th>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
</table> <br>
<input type="submit" value="submit" onclick="submitData()">
In your column loop, you don't want to assign the entire html of the cell. Rather, you need just the value of the select box that is contained in the cell.
In other words: change $(item).html() in your loop on the 'td's to $(item).find('select').val().
You should change this part of code
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index, item) {
arrayItem[headers[index]] = $(item).val();
});
array.push(arrayItem);
});
You are selecting the <td> html, but what you really want is the input and select values.

Javascript code working in JSFiddle but not in my page

The code is copied from jsfiddle, but not working in my webpage. I tried to include the script at bottom and added document.ready function
code in JSfiddle
enter link description here
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form>
<table border = "1" id = "engagements">
<tr>
<th><input type="checkbox" onclick="checkAll(this)"></th>
<th>Organization</th>
<th>Project</th>
<th>Product</th>
<th>Activity</th>
</tr>
<tr>
<td><input type="checkbox" onclick="checkAll(this)"></td>
<td><input type = "text"/></td>
<td><input type = "text"/></td>
<td><input type = "text"/></td>
<td><input type = "text"/></td>
<!--
<td><input type = "text"/></td>
<td><input type = "text"/></td>
<td><input type = "text"/></td>
<td><input type = "text"/></td>
<td><input type = "text"/></td>
-->
</tr>
</table>
<select name = "mode" id = "mode" onchange="addrow('engagements')">
<option value="">Add More Rows with Same Data as Above</option>
<option value="1">1 More</option>
<option value="2">2 More</option>
<option value="3">3 More</option>
<option value="4">4 More</option>
<option value="5">5 More</option>
</select>
</form>
</body>
</html>
Error in webpage
newhtml.html:43 Uncaught ReferenceError: addrow is not defined
at HTMLSelectElement.onchange (newhtml.html:43)
<script src="jquery-3.3.1.min.js">
$(document).ready(function() {
$("#mode").on('change', function () {
var rows = parseInt(this.value);
var lastRow;
for (var i = 0; i < rows; i++) {
lastRow = $('#engagements tr').last().clone();
$('#engagements tr').last().after(lastRow);
}
});
}
</script>
any help will be highly appreciated
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#mode").on('change', function () {
var rows = parseInt(this.value);
var lastRow;
for (var i = 0; i < rows; i++) {
lastRow = $('#engagements tr').last().clone();
$('#engagements tr').last().after(lastRow);
}
});
});
</script>
May be you didn't import jquery properly and you have added in same script tag as comment suggested
$("#mode").on('change', function () {
var rows = parseInt(this.value);
console.log(rows);
var lastRow;
for (var i = 0; i < rows; i++) {
lastRow = $('#engagements tr').last().clone();
$('#engagements tr').last().after(lastRow);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<table border="1" id="engagements">
<tr>
<th>
<input type="checkbox" onclick="checkAll(this)" />
</th>
<th>Organization</th>
<th>Project</th>
<th>Product</th>
<th>Activity</th>
</tr>
<tr>
<td>
<input type="checkbox" onclick="checkAll(this)" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
</table>
<select name="mode" id="mode">
<option value="">Add More Rows with Same Data as Above</option>
<option value="1">1 More</option>
<option value="2">2 More</option>
<option value="3">3 More</option>
<option value="4">4 More</option>
<option value="5">5 More</option>
</select>
</form>
When 'combo box' option is changed, you just declared to invoke function 'addrow' without definition.
You must reference jquery in a separate script tag before you use it like this. Then add your code below it in an another script tag
<script>
$(document).ready(function() {
$("#mode").on('change', function () {
var rows = parseInt(this.value);
var lastRow;
for (var i = 0; i < rows; i++) {
lastRow = $('#engagements tr').last().clone();
$('#engagements tr').last().after(lastRow);
}
});
}
</script>

how to auto increment cell id's when cloning table row using JavaScript?

I've been researching a lot into this and I'm struggling to find a method that works for specifically for what i want to do.
I'm able to clone the rows and auto increment the id name for the row but I can't seem to do this for the td's. For the loop I am using an input where the user says how many row's they want to create. I want to add to a number to the end of the cell id for every time the function loops.
function cloneRow() {
var rowAmmount = document.getElementById("rowAmmount").value;
for (var i = 1; i <= rowAmmount; i++) {
var row = document.getElementById("row"); // find row to copy
var table = document.getElementById("table"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newRow" + i; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
var tag = document.getElementsByTagName('td');
tag.id += i;
}
<table>
<input id="rowAmmount">
<button id="add" onclick="cloneRow()">New Row</button>
<button type="button" onclick="submit()">Submit</button>
<select id="select">
<option value="html">HTML</option>
<option value="packlist">Packlist</option>
</select>
<table>
<thead>
<col width: "130" />
<col width: "130" />
<col width: "130" />
<col width: "130" />
<col width: "130" />
<col width: "130" />
<col width: "130" />
<tr>
<th>Fabric</th>
<th>Fabric Input</th>
<th>Style</th>
<th>Colour</th>
<th>Sizeguide</th>
<th>Image Link</th>
<th>Image</th>
<th>Item Name</th>
<th>Description</th>
</thead>
<tbody id="table">
<tr id="row">
<td><input id="fabric" placeholder="Input"></td>
<td><input id="fabricInput" placeholder="Input 'Yes' 'No' or 'Number'"></td>
<td><input id="style" placeholder="Input"></td>
<td><input id="colour" placeholder="Input"></td>
<td><input id="sizeGuide" placeholder="Input File Name"></td>
<td><input id="imageLink" placeholder="Input"></td>
<td class="output"><img id="image" src=""></output>
</td>
<td class="output"><output id="name"></output></td>
<td class="output"><output id="description"></output></td>
</tr>
I suggest you to do something like this:
Start with an empty table, using class="hidden" to hide the "template" row,
Use .querySelectorAll('tr').length to know how many tr your table contains,
Use .querySelectorAll("*[id]") to get all your elements with ids and a .forEach() loop to change their ids using the number of trs from the above method.
I used the above method to modify the existing ids of the inputs/output/image from the "template" after copying it, but it could be easy to add other ids on other elements (for example the tds).
Snippet:
var table = document.getElementById("table"); // Find table to append to
var row_typical = document.getElementById("row"); // Find row to copy
function cloneRow() {
var rowAmmount = document.getElementById("rowAmmount").value;
for (var i = 1; i <= rowAmmount; i++) {
var clone = row_typical.cloneNode(true); // Copy typical row with children
var num = table.querySelectorAll('tr').length; // Get current number of tr
clone.id = "newRow" + num; // Change id of tr
var ids = clone.querySelectorAll("*[id]"); // Get all elements with id in tr,
ids.forEach(function(elm) { // For all ids
elm.id += num; // Add the num of the tr
});
clone.classList.remove('hidden'); // Remove the "hidden" class
table.appendChild(clone); // Add new row to end of table
}
}
.hidden {
display: none;
}
<input id="rowAmmount" placeholder="Row Amount">
<button id="add" onclick="cloneRow()">New Row</button>
<button type="button" onclick="submit()">Submit</button>
<select id="select">
<option value="html">HTML</option>
<option value="packlist">Packlist</option>
</select>
<table>
<thead>
<tr>
<th>Fabric</th>
<th>Fabric Input</th>
<th>Style</th>
<th>Colour</th>
<th>Sizeguide</th>
<th>Image Link</th>
<th>Image</th>
<th>Item Name</th>
<th>Description</th>
</thead>
<tbody id="table">
<tr class="hidden" id="row">
<td><input id="fabric" placeholder="Input"></td>
<td><input id="fabricInput" placeholder="Input 'Yes' 'No' or 'Number'"></td>
<td><input id="style" placeholder="Input"></td>
<td><input id="colour" placeholder="Input"></td>
<td><input id="sizeGuide" placeholder="Input File Name"></td>
<td><input id="imageLink" placeholder="Input"></td>
<td class="output"><img id="image" src=""></td>
<td class="output"><output id="name"></output></td>
<td class="output"><output id="description"></output></td>
</tr>
</tbody>
</table>
Hope it helps.
Here you go with a solution
function cloneRow() {
var rowAmmount = document.getElementById("rowAmmount").value;
var getTotalRows = document.getElementsByTagName('tbody')[0].children.length;
for (var i = 0; i < rowAmmount; i++) {
var row = document.getElementById("row"); // find row to copy
var table = document.getElementById("table"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newRow" + (getTotalRows + i); // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
var children = document.getElementById('newRow' + (getTotalRows + i)).children;
for (var j = 0; j < children.length; j++) {
var tableChild = children[j].children;
tableChild[0].setAttribute('id', tableChild[0].getAttribute('id') + (getTotalRows + i));
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="rowAmmount">
<button id="add" onclick="cloneRow()">New Row</button>
<button type="button" onclick="submit()">Submit</button>
<select id="select">
<option value="html">HTML</option>
<option value="packlist">Packlist</option>
</select>
<table>
<thead>
<tr>
<th>Fabric</th>
<th>Fabric Input</th>
<th>Style</th>
<th>Colour</th>
<th>Sizeguide</th>
<th>Image Link</th>
<th>Image</th>
<th>Item Name</th>
<th>Description</th>
</tr>
</thead>
<tbody id="table">
<tr id="row">
<td><input id="fabric" placeholder="Input"></td>
<td><input id="fabricInput" placeholder="Input 'Yes' 'No' or 'Number'"></td>
<td><input id="style" placeholder="Input"></td>
<td><input id="colour" placeholder="Input"></td>
<td><input id="sizeGuide" placeholder="Input File Name"></td>
<td><input id="imageLink" placeholder="Input"></td>
<td class="output"><img id="image" src=""></output></td>
<td class="output"><output id="name"></output></td>
<td class="output"><output id="description"></output></td>
</tr>
</tbody>
</table>
Do it like this.
Check the snippet below.
function cloneRow() {
var rowAmmount = document.getElementById("rowAmmount").value;
var added = document.querySelectorAll("tbody#table tr").length;
for (var i = 1; i <= rowAmmount; i++) {
var row = document.getElementById("row"); // find row to copy
var table = document.getElementById("table"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newRow" + (i + added); // change id or other attributes/contents
console.log(clone.id);
table.appendChild(clone); // add new row to end of table
var tag = document.getElementsByTagName('td');
tag.id += i;
}
}
<table>
<input id="rowAmmount">
<button id="add" onclick="cloneRow()">New Row</button>
<button type="button" onclick="submit()">Submit</button>
<select id="select">
<option value="html">HTML</option>
<option value="packlist">Packlist</option>
</select>
<table>
<thead>
<col width: "130" />
<col width: "130" />
<col width: "130" />
<col width: "130" />
<col width: "130" />
<col width: "130" />
<col width: "130" />
<tr>
<th>Fabric</th>
<th>Fabric Input</th>
<th>Style</th>
<th>Colour</th>
<th>Sizeguide</th>
<th>Image Link</th>
<th>Image</th>
<th>Item Name</th>
<th>Description</th>
</thead>
<tbody id="table">
<tr id="row">
<td><input id="fabric" placeholder="Input"></td>
<td><input id="fabricInput" placeholder="Input 'Yes' 'No' or 'Number'"></td>
<td><input id="style" placeholder="Input"></td>
<td><input id="colour" placeholder="Input"></td>
<td><input id="sizeGuide" placeholder="Input File Name"></td>
<td><input id="imageLink" placeholder="Input"></td>
<td class="output"><img id="image" src=""></output>
</td>
<td class="output"><output id="name"></output></td>
<td class="output"><output id="description"></output></td>
</tr>

Categories