I have two input fields, date and miles.
The HTML table has those columns. How do I grab the input values and on "submit" button, insert that data into a new row in the table?
var mileSubmit = document.getElementById("add-mileage");
mileSubmit.addEventListener("click", function () {
const date = document.getElementById("date_miles").value;
const mileage = document.getElementById("miles").value;
console.log(date, mileage);
document
.getElementById("mile_book")
.appendChild(document.createElement("tr"));
});
<form class="miles_form">
<label for="date">Date:</label>
<input type="date" id="date_miles" name="date_miles">
<label>Enter Current Mileage:</label>
<input name="mileage" type="number" id="miles">
</form>
<table id="mile_book">
<tr>
<th>Date</th>
<th>Mileage</th>
</tr>
</table>
Create td elements and append them to the tr element that you created.
var mileSubmit = document.getElementById("add-mileage");
mileSubmit.addEventListener("click", function() {
const date = document.getElementById("date_miles").value;
const mileage = document.getElementById("miles").value;
const row = document.createElement("tr");
const td1 = document.createElement("td");
td1.innerText = date;
row.appendChild(td1);
const td2 = document.createElement("td");
td2.innerText = mileage;
row.appendChild(td2);
document
.getElementById("mile_book")
.appendChild(row);
});
<form class="miles_form">
<label for="date">Date:</label>
<input type="date" id="date_miles" name="date_miles">
<br>
<label>Enter Current Mileage:</label>
<input name="mileage" type="number" id="miles"><br>
<button type="button" id="add-mileage">Add</button>
</form>
<table id="mile_book">
<tr>
<th>Date</th>
<th>Mileage</th>
</tr>
</table>
Related
how to create textbox/text field and button
JavaScript
<script type="text/javascript">
function addItemTodo(){
var value = document.getElementById('item1').value;
var value2 = document.getElementById('item2').value;
var my_table = document.getElementById('todo');
var rows = my_table.getElementsByTagName("tr").length;
row = my_table.insertRow(rows);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell1.innerHTML = value;
cell2.innerHTML = value2;
}
</script>
HTML Code
<input type="text" id="item1" placeholder="item1" size="12">
<input type="text" id="item2" placeholder="item2" size="14">
<button id="add" onclick="addItemTodo()">Add</button>
<table border="1" style="width:50%" id="todo">
<tr>
<th>Input from 'item1'</th>
<th>Input from 'item2'</th>
<th>Text Box</th>
<th>Button</th>
</tr>
</table>
How to append the text box and button, when clicked the add button
You could create your new elements within your Javascript as strings, and then add them to two new cells (insertCell(2) and insertCell(3)) using .innerHTML like so:
function addItemTodo() {
var value = document.getElementById('item1').value;
var value2 = document.getElementById('item2').value;
var my_table = document.getElementById('todo');
var rows = my_table.getElementsByTagName("tr").length;
var row = my_table.insertRow(rows);
row.insertCell(0).innerHTML = value;
row.insertCell(1).innerHTML = value2;
row.insertCell(2).innerHTML = "<input type='text' placeholder='xxx' class='text-box' />";
row.insertCell(3).innerHTML = "<button>Text</button>";
}
.text-box {
width: 50px;
}
<input type="text" id="item1" placeholder="item1" size="12">
<input type="text" id="item2" placeholder="item2" size="14">
<button id="add" onclick="addItemTodo()">Add</button>
<table border="1" style="width:50%" id="todo">
<tr>
<th>Input from 'item1'</th>
<th>Input from 'item2'</th>
<th>Text Box</th>
<th>Button</th>
</tr>
</table>
guys, I am going to develop a simple primary code to get data from the user and add to the table. I have already done the mission but there is some problem I need to ask.
I want to put my operation element (Edit | Delete) also in a cell just like entered first name and last name.
I know how to use "td" for first and last name but I dunno how to add "td" element to put (Edit | Delete) also in a cell of my table
function AddStudents(event){
var x = document.getElementById('fname').value ;
var y = document.getElementById('lname').value ;
console.log("LINE 1");
var ftd = document.createElement('tr');
var ft = document.createElement('td');
var text = document.createTextNode(fname.value);
ft.appendChild(text);
console.log("LINE 2");
var nt = document.createElement('td') ;
var text2 = document.createTextNode(lname.value);
nt.appendChild(text2);
var ot = document.createElement('a');
var neu = document.createElement('td') ;
var od = document.createElement('a');
var sp = document.createElement('a');
ot.innerHTML = ' Edit' ;
od.innerHTML = ' Delete';
sp.innerHTML = ' | ' ;
ot.href = "#" ;
od.href = "#" ;
console.log("LINE 3");
ftd.appendChild(ft)
ftd.appendChild(nt)
ftd.appendChild(ot)
ftd.appendChild(sp)
ftd.appendChild(od)
console.log("LINE 4");
document.getElementById("students").appendChild(ftd);
}
and this my html code :
<input type="text" id="fname" placeholder="First Name">
<input type="text" id="lname" placeholder="Last Name">
</br>
</br>
<button id="add" onclick="AddStudents(this)">Add Student</button>
<h3>List Of Students</h3>
<table id="students" cellpadding = "7px" text-align = "center" border="1">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Operation</td>
</tr>
<tbody></tbody>
</table>
You will need to add the edit and delete links to a td and then append the td to your table.
To do this create a td element, create the links, create a span for the bar and then append the links and span to your td. Now you have a proper table cell which you can append to the table.
As an aside, I recommend you use more descriptive variable names so other people can understand your code easier. It looks like this is likely an assignment your professor would also be able to give you help.
var td = document.createElement('td');
var editLink = document.createElement('a');
var deleteLink = document.createElement('a');
var span = document.createElement('span');
editLink.innerHTML = 'Edit';
editLink.href="#";
deleteLink.innerHTML = 'Delete';
deleteLink.href = "#";
span.innerHTML = '|';
td.appendChild(editLink);
td.appendChild(span);
td.appendChild(deleteLink);
Here is some code which does that, but ensure you understand why this creates a table cell instead of just copy pasting it.
You can simply put a <button> in a <td> element directly:
<input type="text" id="fname" placeholder="First Name">
<input type="text" id="lname" placeholder="Last Name">
</br>
</br>
<button id="add" onclick="AddStudents(this)">Add Student</button>
<h3>List Of Students</h3>
<table id="students" cellpadding = "7px" text-align = "center" border="1">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Operation</td>
<td><button class="" id="btnEdit">Edit</button></td>
<td><button class="" id="btnDelete">Delete</button></td>
</tr>
<tbody></tbody>
</table>
If you're using something like Bootstrap then you can also enter classes where I left empty quotation marks to style the button how you'd like.
You can do this in a better way using jQuery
function AddStudents(){
$("#notification").html('');
var fname= $("#fname").val();
var lname=$("#lname").val();
if(fname!='' && lname!=''){
$("#students tbody").append("<tr>");
$("#students tbody").append("<td>"+fname+"</td>");
$("#students tbody").append("<td>"+lname+"</td>");
$("#students tbody").append("<td><a href='#' class='btnedit'>Edit</a> | <a href='#' class='btndelete'>Delete </a></td>");
$("#students tbody").append("</tr>");
}
else{
$("#notification").html('Please enter First Name and Last Name');
}
}
$(document).on("click",".btnedit",function(){
//Implement Edit functionality here
alert('edit');
});
$(document).on ("click",".btndelete",function(){
//Implement delete functionality here
alert('delete');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='notification'></div>
<input type="text" id="fname" placeholder="First Name">
<input type="text" id="lname" placeholder="Last Name">
</br>
</br>
<button id="add" onclick="AddStudents()">Add Student</button>
<h3>List Of Students</h3>
<table id="students" cellpadding = "7px" text-align = "center" border="1">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Operation</td>
</tr></thead>
<tbody></tbody>
</table>
I added event handling for your Edit and Delete links since it is created runtime.
I have run to a problem with my JavaScript, I'm new to javascript and have just started integrating it with my web application. I have my javascript here:
<script type="text/javascript">
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
}
function findTotal(){
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
This addRow Function here serves as my function in adding a cell each type I click "add entry" Here's a bit of my HTML:
<div class="col-md-5" style="display: inline-block; ">
<div class="jumbotron">
<h2>Type in Nature of Collection...</h2>
<form>
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nature of Collection</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<h6> <label>Date:<span></span>
</label>{{date}}</h6>
<h3><fieldset disabled>
<label>Total </label>
<input type = "text" name = "total" id="total"><br></p>
</fieldset></h3>
</div><!-- COL5 END -->
I just took out the HTML codes that are involved with this problem.
I am using addRow() to add each function. The Second column gets a numeric value. For example. 200.00 or 232 r 2.2 What I wanted to do is to get the total while I'm adding it real-time. I have inspected the adding of cells in the developer options in the Mozilla browser it shows that the digits are falling to each of the tr's second td.
So I used var arr = document.querySelectorAll("#datatable td:nth-child(2)");
in my totaling function hoping that I would get the list and evaluate it. However I am unable to do this, there's nothing showing in my total UI.
or.. Am I really getting my amounts in the using that?
This worked when I was implementing it using checkboxes so I know how it would work. Every time I add a value it shows on the total box whenever something gets added. But here it's different. I found an answer that says nth-child gets non-live object list. Should I make the objects live before I can evaluate it in the total?
I'm really stuck at this part. If you have any ideas on how to fix this please do help me. or if you could give me an alternative way to add cells then totaling it real-time that would also help.
I could make do with the submission type, but the page gets reloaded and it will be a hassle for the user to scroll down again. This part of the app, when you add a cell it just pops there without the page reloading, as to why I used javascript to implement this function.
Here are pics of how it works:
Console shows:
Any help is appreciated. Thank you very much!
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
findTotal();
}
function findTotal(){
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
var enter_value = Number(arr[i].textContent) //id u want do parseInt(enter_value)
if(enter_value)
tot += Number(arr[i].textContent);
}
document.getElementById('total').value = parseInt(tot);
}
<div class="col-md-5" style="display: inline-block; ">
<div class="jumbotron">
<h2>Type in Nature of Collection...</h2>
<form>
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nature of Collection</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<h6> <label>Date:<span></span>
</label>{{date}}</h6>
<h3><fieldset disabled>
<label>Total </label>
<input type = "text" name = "total" id="total"><br></p>
</fieldset></h3>
</div><!-- COL5 END -->
This should work.
Not the best code but a hot fix for yours.
I recomend you to look into html data- attributes
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
findTotal();
}
function findTotal(){
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
tot += parseInt(arr[i].innerHTML);
}
document.getElementById('total').value = tot;
}
<div class="col-md-5" style="display: inline-block; ">
<div class="jumbotron">
<h2>Type in Nature of Collection...</h2>
<form>
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nature of Collection</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<h6> <label>Date:<span></span>
</label>{{date}}</h6>
<h3><fieldset disabled>
<label>Total </label>
<input type = "text" name = "total" id="total"><br>
</fieldset></h3>
</div><!-- COL5 END -->
This is the faulty code:
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
In here, arr is a collection of DOM nodes, matching #datatable td:nth-child(2) selector. You're trying to sum up their value properties. However, <td> elements do not have a value. You might want to try getting their innerText property:
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].innerText))
tot += parseInt(arr[i].innerText);
}
Note you're closing a </p> you never opened just after the total field. There might be other problems with your script, but this one caught my eye.
See it working here. (I've stripped it down to minimum).
I am adding rows in table and deleting, this works fine. using oninput="" event i am also able to calculate the total cost by calling javascript function.
Now, the moment i add <form></form>, neither am able to add rows nor moving any forward. I am new to javascript, and have no clue what is going on. please help somebody.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i <= arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>
Inside the form tags buttons tend to do the default action which is submit.
So change your button from,
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
to
<input type="button" onclick="myCreateFunction()" value="Create row">
<input type="button" onclick="myDeleteFunction()" value ="Delete row">
You have to add Input tag instead of button tag. Because button tag in form specifies default submit event on-click so your form submitted when you add any row and also refresh.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<input type="button" onclick="myCreateFunction()" value="Create row" />
<input type="button" onclick="myDeleteFunction()" value="Delete row" />
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i < arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>
I have the following problem. I would like to add some data to a table using label values (in this case 7 & 5) but every time I try to add a value, the cells show the message "undefined". The main idea is to create a table which values are going to be used to draw a bar chart (graph) using the highcharts library
<h2>Add Row in JavaScript</h2>
<table id="table" cellspacing="0" border="1">
<tbody>
<tr>
<td>Name</td>
<td>Address</td>
</tr>
</tbody>
</table>
<button onclick="javascript:addRow('table')">Add row</button>
<br></br>
<label id="txt1" value="7" text="a">label 1</label>
<label id="txt2" value="5" text="b">label 2</label>
Script:
function addRow(id){
var label = ($("#txt1").val());
var label2 = ($("#txt2").val());
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
var data1 = document.createElement("td");
data1.appendChild(document.createTextNode(label.value));
var data2 = document.createElement("td");
data2.appendChild(document.createTextNode(label2.value));
row.appendChild(data1);
row.appendChild(data2);
tbody.appendChild(row);
}
Example in JFiddle
Code
Highcharts library
Code
It seems you have taken label instead of textbox, anyway below is working code.
function addRow(id) {
var label = ($("#txt1").attr("value"));
var label2 = ($("#txt2").attr("value"));
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
var data1 = document.createElement("td");
data1.appendChild(document.createTextNode(label));
var data2 = document.createElement("td");
data2.appendChild(document.createTextNode(label2));
row.appendChild(data1);
row.appendChild(data2);
tbody.appendChild(row);
}