Why ismy nameValue, amountValue and dateValue undefined? - javascript

I try to append a tr element to a tbody element, it works but when the tr is shown, the td is undefined, NaN and undefined. I try to get the value from the input elements and submit the tr of data to tbody.
Do you guys have any idea of where i went wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense tracker remake</title>
</head>
<body>
<h1>Expense tracker</h1>
<div class="bold" id="name">Name of Item: </div> <input type="text">
<div class="bold" id="amount">Amount: </div> <input type="text">
<div class="bold" id="date">Date: </div> <input type="date">
<button id="submit">Submit</button> <button id="clear">Clear all</button>
<table>
<thead>
<th>Name</th>
<th>Amount</th>
<th>Date</th>
</thead>
<tbody id="tbody">
</tbody>
</table>
<script>
var tbody = document.getElementById("tbody");
var name = document.getElementById("name");
var amount = document.getElementById("amount");
var date = document.getElementById("date");
var clear = document.getElementById("clear");
var submit = document.getElementById("submit");
submit.addEventListener("click",function(){
var nameValue = name.value;
var amountValue = amount.value;
var dateValue = date.value;
var tr = document.createElement("tr");
tr.innerHTML += "<td>"+nameValue+ " </td><td>"+ + amountValue+ "</td><td>" + dateValue+ "</td>";
tbody.appendChild(tr);
console.log(name.value);
})
</script>

You have added an extra + in html string which you are using to append tr element.
tr.innerHTML += "<td>"+nameValue+ " </td><td>" + amountValue+ "</td><td>" + dateValue+ "</td>";

You made two mistakes:
Your name, amount and date elements are a divs, not an inputs, so when you trying to read from name.value you are trying to read from empty div.
Some words in javascript are reserved and sometimes when you using those your code could works in strange way. One of those words is name. Source.
The working demo of your code you can find here: jsFiddle.net.
As you can see, I've just pointed to input instead of div (by calling nextElementSibling because your input is a next element of your div) and changing variables names for avoiding name conflicts. Also, I have removed unnecessary doubled plus signs from tr.innerHtml += ....

Related

How to show a table after submit a form

I have a form to enter scores and calculate the average score. After entering the form, the user clicks on the submit button, it will display a table of scores that have been entered before along with 2 buttons. First button will add a column of average scores to the form and the second button will determine if any average score is >= 8 the letter in that column will be highlighted in red.
Here is my code.
Here is my HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--
This is a form for users to enter scores
-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td><input name="math" id="math" type="text" /></td>
</tr>
<tr>
<td>Physics:</td>
<td><input name="physics" id="physics" type="text" /></td>
</tr>
<tr>
<td>Chemistry:</td>
<td><input name="chemical" id="chemical" type="text" /></td>
</tr>
<td>
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<!--
This table below must not show when user access the browser,
it only show after user enter score and click the "Submit" button with 2 button below
-->
<table id="tableScore" border="2" width="100%">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average Score</th> <!-- This still can not show -->
</table>
<div>
<button onclick="">Show the average score</button> <!--This will show the average score column-->
<button onclick="">Best student</button> <!--Determine if any average score >= 8 hightlight all the text into red-->
</div>
</body>
</html>
My JS file:
var testScore = {
name: "",
math: 0,
physical: 0,
chemistry: 0
};
var i = 0; /* This variable is incremented by 1 every time the user clicks the "Submit" button. Display the "No" column, and the position of rows when added to the table
*/
// Show a table after submit
function score_table() {
document.getElementById("tableScore").style.display="block";
// Gathering the data after submit
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physical = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = "?";
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Insert row
var table = document.getElementById("tableScore");
var row = table.insertRow();
var number = row.insertRow();
var name = row.insertRow();
var math = row.insertRow();
var physics = row.insertRow();
var chemistry = row.insertRow();
var avg = row.insertRow();
number.innerHtml = i;
name.innerHtml = testScore.name;
math.innerHtml = testScore.math;
physics.innerHtml = testScore.physics;
chemistry.innerHtml = testScore.chemistry;
avg.innerHtml = "?";
/** I need help, How to calculate the average score and if the average
score is >= 8 then hightlight every text in that row into red
*/
}
Finally, my CSS file:
/* I just do to hidden the table, because i struggle with JS file :)) */
#tableScore {
display: none;
}
There are a few problems with your source code.1. you used testScore.avg, but you did not declare avg in the variable testScore.2.it is better to use type="number" as the input for the scores, or you need to add pattern="yourpattern" to disallow input of alphabets and special characters.3.innerHtml is not the correct syntax, use innerHTML instead.4.You only need to use one insertRow().As for the other fields, you should use insertCell()instead.5.You need to insert a number into the insertRow/insertCell method. Eg.insertRow(x);
As for calculating the average, you can easily find it by adding the three fields and dividing them by the number of fields.It is also better to hide the whole division instead of just the table, don't you think it's weird that you have button in the website but it does nothing?You can also add the input fields inside a form, so that you can add mandatory attribute to the fields to ensure no null values will be added into the table. You also need to add i++; in your function, otherwise all the numbers in the column "No" of your table will be the same number.To hide/show a certain column in the table, you can use nth-child in the css/js.Last and the most important issue, check your spelling. Some you use physics, some use physical, some use chemistry, but some use chemical, this is very confusing and will bring a hard time during maintenance or debugging in the future. You can also easily encounter a lot of errors this way. Eg. you declared as testScore.physical, but in the function you used testScore.physicsChoose one variable name and stick with it.
var testScore = {
name: "",
math: 0,
physics: 0,
chemistry: 0,
avg: 0
};
var i = 1;
/* This variable is incremented by 1 every time the user clicks the "Submit" button. Display the "No" column, and the position of rows when added to the table
*/
// Show a table after submit
function score_table() {
document.getElementById("divTable").style.display = "block";
// Gathering the data after submit
testScore.name = document.getElementById("name").value;
testScore.math = document.getElementById("math").value;
testScore.physics = document.getElementById("physics").value;
testScore.chemistry = document.getElementById("chemical").value;
testScore.avg = (parseFloat(testScore.math) + parseFloat(testScore.physics) + parseFloat(testScore.chemistry)) / 3;
document.getElementById("name").value = "";
document.getElementById("math").value = "";
document.getElementById("physics").value = "";
document.getElementById("chemical").value = "";
// Insert row
var table = document.getElementById("tableScore");
var row = table.insertRow(i);
var number = row.insertCell(0);
var name = row.insertCell(1);
var math = row.insertCell(2);
var physics = row.insertCell(3);
var chemistry = row.insertCell(4);
var avg = row.insertCell(5);
number.innerHTML = i;
name.innerHTML = testScore.name;
math.innerHTML = testScore.math;
physics.innerHTML = testScore.physics;
chemistry.innerHTML = testScore.chemistry;
avg.innerHTML = testScore.avg;
i++;
/** I need help, How to calculate the average score and if the average
score is >= 8 then hightlight every text in that row into red
*/
}
function showAvg() {
document.getElementById("tableScore").querySelector("th:nth-child(6)").style.display = "block";
var colAvg = document.getElementById("tableScore").querySelectorAll("td:nth-child(6n)");
for (var i = 0; i < colAvg.length; i++) {
colAvg[i].style.display = "block";
}
}
function showBest() {
var colAvg = document.getElementById("tableScore").querySelectorAll("td:nth-child(6n)");
var rowAvg = document.getElementById("tableScore").querySelectorAll("tr:nth-child(1n)");
for (var i = 0; i < colAvg.length; i++) {
var avg = parseFloat(colAvg[i].innerText);
if (avg >= 8) {
rowAvg[i + 1].style.background = "red";
} else {}
}
}
/* I just do to hidden the table, because i struggle with JS file :)) */
#divTable {
display: none;
width: 100%;
}
#tableScore th:nth-child(6),
#tableScore td:nth-child(6) {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="css/main.css" />
</head>
<body>
<script src="js/script.js"></script>
<h1 align="center">Class Marksheet</h1>
<!--
This is a form for users to enter scores
-->
<table align="center">
<tr>
<td>Name:</td>
<td><input name="name" id="name" type="text" /></td>
</tr>
<tr>
<td>Math:</td>
<td><input name="math" id="math" type="number" /></td>
</tr>
<tr>
<td>Physics:</td>
<td><input name="physics" id="physics" type="number" /></td>
</tr>
<tr>
<td>Chemistry:</td>
<td><input name="chemical" id="chemical" type="number" /></td>
</tr>
<td>
<button type="submit" onclick="score_table()">Submit</button>
</td>
</table>
<!--
This table below must not show when user access the browser,
it only show after user enter score and click the "Submit" button with 2 button below
-->
<div id="divTable">
<table id="tableScore" border="2">
<th>No</th>
<th>Name</th>
<th>Math</th>
<th>Physics</th>
<th>Chemistry</th>
<th>Average Score</th>
<!-- This still can not show -->
</table>
<button onclick="showAvg()">Show the average score</button>
<!--This will show the average score column-->
<button onclick="showBest()">Best student</button>
<!--Determine if any average score >= 8 hightlight all the text into red-->
</div>
</body>
</html>

Append data to html table

I'm trying to add more data to the table below using JavaScript.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home Page</title>
<script type="text/javascript" src="assets/style.js"></script>
</head>
<body>
<br><br><br><br><br>
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button> <br><br><br><br><br>
<table>
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
<div id="addDataHere">
</div>
</table>
</body>
</html>
style.js Used is below:
function addData(){
var personName = document.getElementById("personName").value;
//console.log(personName);
var getOlderInformation = document.getElementById("addDataHere").innerHTML;
document.getElementById("addDataHere").innerHTML = getOlderInformation + "<tr><td>" + personName + "</tr></td>";
}
Expected Output Results:
Client Names James Bond 007 Tom Cruise ............ ............ ............ ............
This should get you started.
function addData() {
var personName = document.getElementById("personName").value;
var newRow = document.createElement("tr");
var newCell = document.createElement("td");
newCell.innerHTML = personName;
newRow.append(newCell);
document.getElementById("rows").appendChild(newRow);
document.getElementById("personName").value = '';
}
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button> <br><br><br><br><br>
<table>
<tr>
<th>Client Name</th>
</tr>
<tbody id="rows">
<tr>
<td>James Bond 007</td>
</tr>
</tbody>
</table>
You were on the correct path, but an important note is that you were trying to use a div inside of a table. A table has very specific structure that has to be matched if you want it to render properly.
You are able to put div elements inside of a td or a th, but not inside of the table element itself. Check out this link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
you can use a list to match what you need here's the code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home Page</title>
</head>
<body>
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button>
<p>Client Name</p>
<ul id="mylist">
<li>James Bond 007</li>
</ul>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
and the use adddata() function code like this
`function addData(){
var mylist=document.getElementById("mylist");
var personName=document.getElementById("personName").value;
var node = document.createElement("LI");
var textnode = document.createTextNode(personName);
node.appendChild(textnode);
mylist.appendChild(node);
}`
I hope this helps you :)
You can use an approach similar to what you are attempting: getting the innerHTML, appending some new html, and then replacing the innerHTML. But, you need to get the innerHTML of your table (not the element you nested inside of it).
For example (replaced your button onclick with an event listener).
const personName = document.getElementById('personName');
const appendButton = document.getElementById('appendButton');
const nameTable = document.getElementById('nameTable');
appendButton.addEventListener('click', (event) => {
let content = nameTable.innerHTML;
content += '<tr><td>' + personName.value + '</td></tr>';
nameTable.innerHTML = content;
});
<input type="text" id="personName" autofocus>
<button type="button" id="appendButton">Append Information</button>
<table id="nameTable">
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
</table>
Depending on the complexity of what you are doing, it may be faster to go the createElement / appendChild route suggested in the other answers if you also use use createDocumentFragment. Another example:
appendButton.addEventListener('click', (event) => {
const frag = document.createDocumentFragment();
const tr = document.createElement('tr');
const td = document.createElement('td');
td.appendChild(document.createTextNode(personName.value));
tr.appendChild(td);
frag.appendChild(tr);
nameTable.appendChild(frag);
});
<input type="text" id="personName" autofocus>
<button type="button" id="appendButton">Append Information</button>
<table id="nameTable">
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
</table>
You want to use appendchild. Check this out for some
Good examples https://www.w3schools.com/jsref/met_node_appendchild.asp . You want to loop through the data adding a row to a table , one row at a time

How to load my json data into a html table and make the rows as radio buttons using pure Javascript?

I have a json response:
var jsondata = dojo.fromJson(response);
I have a string
var jsonString = jsondata.items;
jsonString is the JSON file
jsonString="[
{macAddress:'aa:bb:Cc',domainName:'NMS',Priority:'first'},
{macAddress:'ea:fb:Ca',domainName:'Network',Priority:'third'},
{macAddress:'ca:bb:Ca',domainName:'Mesh',Priority:'second'}
]";
Now I want to access the first object {macAddress:'aa:bb:Cc',domainName:'NMS',Priority:'first'} by jsonString[0].
This is not working. This displays "[", which is the first element and not the first object.
I have also tried
jsondata.items[0];
jsondata[Object.keys(jsondata)[0]];
jsondata[1];
Everything says "Undefined".
Could someone please help?I need to extract this data and put it in a table with rows as radio buttons
I think there is an error in your json string, try to validate json using jsonlint.com
Please find the working code below :
$(document).ready(function(){
var jsonString = '[{"macAddress": "aa:bb:Cc","domainName": "NMS","Priority": "first"},{"macAddress": "ea:fb:Ca","domainName": "Network","Priority": "third"},{"macAddress": "ca:bb:Ca","domainName": "Mesh","Priority": "second"}]';
var row = '';
$.each($.parseJSON(jsonString), function(index, value){
row += '<tr><td> </td><td><input type="radio" name="test" /> '+ value.macAddress +'</td></tr>';
});
$('#tbl tbody').html(row);
});
<!doctype html>
<html>
<head>
<title>Stackoverflow</title>
</head>
<body>
<div class="container">
<table id="tbl">
<thead>
<tr>
<th> </th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</body>
</html>
var jsonString = '[{"macAddress": "aa:bb:Cc","domainName": "NMS","Priority": "first"},{"macAddress": "ea:fb:Ca","domainName": "Network","Priority": "third"},{"macAddress": "ca:bb:Ca","domainName": "Mesh","Priority": "second"}]';
var jsonObject = JSON.parse(jsonString);
//build head
var head = '<tr>';
for(key in jsonObject[0]){
head +='<th> </th><th>'+key+'</th>';
}
head +='</tr>';
//build rows
var rows = jsonObject.map(function(element){
var row = '<tr>';
for( key in element){
row += '<td> </td><td><input type="radio" name="'+key+'" /> '+ element[key] +'</td>';
}
row += '</tr>';
return row;
});
//adding to table
var tbl_head = document.getElementById('tbl').getElementsByTagName('thead')[0];
var tbl_body = document.getElementById('tbl').getElementsByTagName('tbody')[0];
tbl_head.innerHTML = head;
tbl_body.innerHTML = rows.join('');
<!doctype html>
<html>
<head>
<title>Stackoverflow</title>
</head>
<body>
<div class="container">
<table id="tbl">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>

How to set effect dynamically in javascript

In this JSFiddle demo, i tried to add a row dynamically only knowing the id of one of the previous element of the table. The code works perfectly, otherwise i want to beautify it. In particular i wish to highlight the new inserted row, using this property:
.effect("highlight", color: '#4BADF5'}, 1000);
Any suggestions?
Thanks
First of all - you need to add the jQuery UI lib.
Second - your algorithm is not optimal one.
Please find an optimal solution below:
var myClick = function() {
var nome = "Hello";
var rowId = "120"
var row = "<tr><td>" + nome + "</td></tr>";
var newTr = $(".mytable1 tr #" + rowId).parent().after(row);
newTr.next().effect("highlight", { }, 2000);
};
$('#button').click(myClick);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<input type="button" id="button" value="Add"/>
<table class="mytable1">
<tr><td id="12">1.0</td></tr>
<tr><td id="20">1.1</td></tr>
<tr><td id="120">1.2</td></tr>
<tr><td id="260">1.3</td></tr>
<tr><td id="2">1.4</td></tr>
<tr><td id="100">1.5</td></tr>
<tr><td id="23">1.6</td></tr>
</table>

"Add Row" logic not working as expected

It has taken me days to come up with the following, and now I'm realizing that it still doesn't work. My "add row" button isn't working properly. What am I missing?
<table>
<tr>
<th>field</th>
<th>comparison</th>
<th>value</th>
</tr>
<tr>
<td>
<select style="width:5em;" class="field">
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
<td><button id="add">Add row</button></td>
</tr>
</table>
$('#tableSearchMainAccount1 tr').each(function() {
var td = '';
// used to skip table header (if there is)
if ($(this).find("td:first").length > 0) {
$(this).find('option:selected').each(function() {
td = td + $(this).text() + ',';
});
td = td + $(this).find('input').val();
filt[ctr] = td;
ctr += 1;
}
});
//alert(filt); //alert output like name,equals,ann,age,equals,11
$('#add').live('click', function() {
var $lastTr = $('table tr:last');
console.log($lastTr);
$lastTr.clone().insertAfter($lastTr);
// Remove the button from the previous tr, otherwise each row will have it.
$('#add', $lastTr)
.replaceWith('<button class="remove_row">Remove row</button>');
});
$('.remove_row').live('click', function() {
$(this).closest('tr').remove();
});
From the discussion in the comments, it appears you have not referenced jQuery.
Add the following to your <head></head> section:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
There are many other CDNs that host jQuery for you, or you can download it yourself. All of these details can be found on http://jquery.com/download/.
So that your markup looks something like the following:
<!DOCTYPE html>
<html>
<head>
<title>My jQuery Project</title>
<script src="jquery-1.8.3.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<table>...</table>
</body>
</html>
Note that I also referenced another external file called "scripts.js". This is where you could place all of your JavaScript and jQuery logic.
$(document).ready(function(){
/* Wrapping your code with a document-ready
block will ensure that the DOM will be
ready before your code runs
*/
});
replace
<table>
with
<table id="tableSearchMainAccount1">
would be my starter for 10.

Categories

Resources