Remove values from input fields when creating a new table row - javascript

I'm trying to create a new role but I want a row where there isn't any value in the textfield.
<form action="Fruits" method="Post" enctype="multipart/form-data">
<table id="myTable">
<c:forEach items="${fruits}" var="val" varStatus="count">
<thead>
<tr>
<th>Fruit</th>
<th>Color</th>
</thead>
<tbody>
<td><input type="text" name="name" id="name" value="${val.name}"></td>
<td><input type="text" name="color" id="color" value="${val.color}"></td>
</tbody>
</table>
<button type="button" class="btn btn-default json-editor-btn-add" onclick="myFunction()">Add</button>
</form>
For now whenever I create a new role, it gives me the values of the first row and fill the text field. Is there a way where I just create a row where it doesnt have any values.
function myFunction(){
var table = document.getElementById("myTable");
var first_tr = table.firstElementChild;
var second_tr = first_tr.nextElementSibling;
var tr_clone = first_tr.cloneNode(true);
var tb_clone = second_tr.cloneNode(true);
table.append(tr_clone);
table.append(tb_clone);
}
I'm expecting a blank field text for all of the column upon creating a row

Instead of cloning previous rows create a row template using a template/string literal that you can insert before the end of the tbody element.
Note: you don't have any rows in your current table's - you just have two cells. You also can't have multiple cells with the same id. Ids are supposed to be unique within a document. If you have to identify cells separately you should use a data attribute instead.
const rowTmpl = `<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="color"></td>
</tr>`;
const tbody = document.querySelector('tbody');
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
function handleClick(e) {
tbody.insertAdjacentHTML('beforeend', rowTmpl);
}
<table>
<thead>
<tr><td>Fruit</td><td>Color</td></tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" value="Apple" name="name"></td>
<td>
<input type="text" value="Red" name="color">
</td>
</tr>
</tbody>
</table>
<button type="button">Add row</button>

Add below lines in your function.
let array_of_input = tb_clone.querySelectorAll('input');
array_of_input.forEach(cur => {
cur.value = '';
})
Your final function looks like this.
function myFunction() {
var table = document.getElementById("myTable");
var first_tr = table.firstElementChild;
var second_tr = first_tr.nextElementSibling;
var tr_clone = first_tr.cloneNode(true);
var tb_clone = second_tr.cloneNode(true);
table.append(tr_clone);
table.append(tb_clone);
let array_of_input = tb_clone.querySelectorAll('input');
array_of_input.forEach(cur => {
cur.value = '';
})
}

Related

Clone table and display after button

Great day Community,i'm facing clone whole table problem, if it have solution of clone several row it will be helping a lots.
If using document.getElementsByTagName("table")[2]; it can clone the table and put it in body because i'm using document.body.appendChild(myClone) to do it.
Here is some code:
Solution 1:
function myFunction() {
myTable = document.getElementsByTagName("table")[2]; // doesn't use any table id
myClone = myTable.cloneNode(true);
var y = document.body.appendChild(myClone);
}
Solution 2:
function myFunction() {
var x = document.getElementById("0"); // using this to find auto genereate id for table
test = x.cloneNode(true);
}
Html Display:
<table>
<tr>
<td>
<table id="0">
<tr>
<td><span></span>Name:<input type="text" value="Tom"/> </td>
<td><span> </span>Age:<input type="text" value="25"/> </td>
<td><span> </span>Email:<input type="text" value="tom#gmail.com"/> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="1">
<tr>
<td><span></span>Name:<input type="text" value="Alice"/> </td>
<td><span> </span>Age:<input type="text" value="22"/> </td>
<td><span> </span>Email:<input type="text" value="alice#gmail.com"/> </td>
</tr>
</table>
<input type="button" onclick="myFunction()"/>
</td>
</tr>
</table>
Expected result clone the table after the button, the table inside will not have more than 5.
Please help thank you.
Although Dominic Amal Joe F's answer was on the right track, it had some flaws, as well as the structure of the OP table. I think this code would work properly:
function myFunction(){
// get main table body
var tableBody = document.getElementById('mytable').children[0];
// get existing rows
var rows = tableBody.children.length;
// clone the last row (which contains the last table)
var newRow = tableBody.children[rows-1].cloneNode(true);
// get the new row table
var newTable = newRow.children[0].children[0]
// change the table id
newTable.setAttribute('id', rows);
// reset the inputs values
var cells = newTable.children[0].children[0].children;
for (var i=0; i<cells.length; i++) {
cells[i].children[1].value = "";
}
// append the new row to the main table body
tableBody.appendChild(newRow);
}
<table id="mytable">
<tr>
<td>
<table id="0">
<tr>
<td><span>Name:</span><input type="text" value="Tom"/></td>
<td><span>Age:</span><input type="number" value="25"/></td>
<td><span>Email:</span><input type="email" value="tom#gmail.com"/></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="1">
<tr>
<td><span>Name:</span><input type="text" value="Alice"/></td>
<td><span>Age:</span><input type="number" value="22"/></td>
<td><span>Email:</span><input type="email" value="alice#gmail.com"/></td>
</tr>
</table>
</td>
</tr>
</table>
<button onclick="myFunction()">Clone</button>
I feel the following code will help you.
HTML
<table>
<button onclick="myFunction()">clone</button>
<tr>
<table id="parent-table">
<tr id="parent-row">
<td><span></span>Name:<input type="text" value="Tom"/> </td>
<td><span> </span>Age:<input type="text" value="25"/> </td>
<td><span> </span>Email:<input type="text" value="tom#gmail.com"/></td>
</tr>
</table>
</tr>
</table>
JavaScript
function myFunction(){
let parentTable = document.getElementById("parent-table");
let parentRow = document.getElementsByTagName('tr')
let clone = parentRow[1].cloneNode(true);
parentTable.appendChild(clone)
}

How to clone a <tr> in a table with Javascript

I want to duplicate the second <tr> everytime I click button add, as it shows in here, I mean I want to whenever I click on the button add a new <tr> will be added that do the same thing as the previous one.
<form id="frm1" action="Calculate.html">
<table id= "myTable">
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
<tr id= "rowToClone">
<td>
<select id= "products">
<option value="80">Product-A</option>
<option value="80">Product-B</option>
<option value="80">Product-C</option>
<option value="80">Product-D</option>
<option value="16">Product-E</option>
</select>
</td>
<td><input type="number" id="ndc" placeholder=""></td>
<td><p id="ndpc"></p></td>
<td><p id="pu"></p></td>
<td><p id="ptpp"></p></td>
</tr>
</table>
<input type="button" onclick="Calculate()" value="calculate">
<input type="button" onclick="AddSelect()" value="Add">
I want it to do the same whole thing, I tried but never got successful the second part I am stuck to
first part:
function Calculate() {
var e = document.getElementById("products");
var productValue = e.options[e.selectedIndex].value;
document.getElementById("ndpc").innerHTML = productValue;
document.getElementById("ndpc").value = productValue;
if (e.selectedIndex === 0){
document.getElementById("pu").value = 21.2;
}
else if (e.selectedIndex === 1) {
document.getElementById("pu").value = 25.7;
}
else if (e.selectedIndex === 2 || e.selectedIndex === 3 ) {
document.getElementById("pu").value = 14;
}
else {
document.getElementById("pu").value = 6;
}
var pu = document.getElementById("pu").value;
document.getElementById("pu").innerHTML = pu;
var ndc = document.getElementById("ndc").value;
var ndpc = document.getElementById("ndpc").value;
var Result = ndc * ndpc * pu;
document.getElementById("ptpp").innerHTML = Result;
};
the second part that I want to solve:
function AddSelect(){
var row = document.getElementbyId("rowToClone");
var table = document.getElementById("myTable");
var clone = row.cloneNode(true);
clone.id = "New";
function createRow() {
//I don't know what to do.
} };
I am new to Javascript obviously, please help me.
When using methods such as cloneNode(), or createElement() you'll need to append the new node to the DOM or it'll just float around aimlessly. Also, when cloning a node, keep in mind that if it and/or its children have any #ids, you'll end up having duplicated #ids which is super invalid. You should either change the #ids on all clones or do away with #ids on cloned nodes and use classes, tags, attributes, etc. instead.
In this demo, I replaced the form controls' #ids with name attribute since that's all you need to have in order to submit values from a <form> to a server (that and a <input type='submit'> button of course).
Demo
function addSelect() {
var T = document.getElementById('xTable');
var R = document.querySelectorAll('tbody .row')[0];
var C = R.cloneNode(true);
T.appendChild(C);
}
<form id="frm1" action="Calculate.html">
<table id="xTable">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
<tr class="row">
<td>
<select name="products">
<option value="80">Product-A</option>
<option value="80">Product-B</option>
<option value="80">Product-C</option>
<option value="80">Product-D</option>
<option value="16">Product-E</option>
</select>
</td>
<td><input type="number" name="ndc" placeholder=""></td>
<td>
<p id="ndpc"></p>
</td>
<td>
<p id="pu"></p>
</td>
<td>
<p id="ptpp"></p>
</td>
</tr>
</table>
<input type="button" onclick="addSelect()" value="Add">
</form>

How to add dynamic rows with dynamic id in table using jquery

I have a different rows with different columns . I want to add those dynamically.
As my code is
$('.add-invoice-item').click(function (e) {
e.preventDefault();
row += 1;
var elem = $(".temp-tr tr").clone();
elem.find('.alt_date').attr('id', 'invi_date' + row);
$('.invoice-items').append(elem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody class="invoice-items">
</tbody>
<div class="temp-tr hidden-element">
<table>
<tr>
<input type="text" name = "text1"/>
</tr>
<tr>
<input type="text" name = "text2"/>
</tr>
</table>

How to get table row index when the column textbox value change using jQuery

I want to get row index and text box values when the table price text box value changes. At the moment I'm getting some undefined value.
HTML
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control product">
</td>
<td>
<input type="text" oninput="javascript:GetValue(this);" class="form-control price">
</td>
</tr>
</tbody>
</table>
JavaScript
function GetValue(oTextBox) {
var price = oTextBox.value;
var product = oTextBox.parent().prev().innerHTML.value;
var rowindex = oTextBox.closest('tr').index();
}
I get this error:
TypeError: oTextBox.parent is not a function
var product = oTextBox.parent().prev().innerHTML.value;
You need to wrap oTextBox in $ in order to use jQuery methods. That's because oTextBox ... or ... this is a DOM element and not a jQuery object. Thus:
var product = oTextBox.parent().prev().innerHTML.value;
Should be:
var product = $(oTextBox).parent().prev().find('input').val();
And:
var rowindex = oTextBox.closest('tr').index();
Should be:
var rowindex = $(oTextBox).closest('tr').index();
SUGGESTION
I would encourage you to not use inline JS:
<input type="text" class="form-control price">
Then your jQuery would be:
$(function() {
$('input.price').on('input', function() {
var price = this.value;
var product = $(this).parent().prev().find('input').val();
var rowindex = $(this).closest('tr').index();
//....
});
});
Replace oTextBox in the function by $(oTextBox) and then you can use html() instead of innerHTML, like so
$(oTextBox).parent().prev().html()

Adding Tables Rows and Cells Dynamically Using Javascript

I was trying to add a table row with data in my HTML table using Javascript but it seems I it can't add. Why is that?
<html>
<head>
<title>
</title>
<script>
function addUser(){
var tbl = document.getElementById('datatable');
var lastRow = tbl.rows.length;
var iteration = lastRow+1;
var row = tbl.insertRow(lastRow);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
}
</script>
</head>
<body>
<table border = 1 id = "datatable">
<tr>
<td>ID</td>
<td>NAME</td>
<td>ADDRESS</td>
</tr>
<tr>
<td>1</td>
<td>Something</td>
<td>Something</td>
</tr>
<tr>
<td>2</td>
<td>Foo</td>
<td>bar</td>
</tr>
</table>
<form id = "myForm" onsubmit = "addUser()">
ID:<input type = "text" name = "txtID"><br />
NAME:<input type = "text" name = "txtName"><br />
ADDRESS:<input type = "text" name = "txtAddress"><br />
<input type = "submit" value = "Add Item">
</form>
</body>
</html>
what you need is not to submit a form
just simply an onclick event could help.
<input type = "button" value = "Add Item" onclick="addUser()">
It's because you're submiyting a form. First your AddUSer is called and works, but the page is reloaded and what you see is the initial page.

Categories