JS How to calculate the values of rows in a table? - javascript

For example, there is such a table, with cells FootballPlayers, Swimmers, BasketballPlayers and Sum, in which rows are added in turn, how i can count and record in the Total row how many football players, swimmers and basketball players are added?
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled=true;
}
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k=0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k=0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k=0;
}
var sum1 = (f1k+f2k+f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1=tbody.insertCell(0);
r1.innerHTML="";
var r2=tbody.insertCell(1);
r2.innerHTML=f1;
var r3=tbody.insertCell(2);
r3.innerHTML=f2;
var r4=tbody.insertCell(3);
r4.innerHTML=f3;
var r4=tbody.insertCell(4);
r4.innerHTML=sum1;
if(document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled=false;
}
}
#tg {border-collapse:collapse;border-spacing:0;}
#tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg .tg-yw4l{vertical-align:top}
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;" >Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e"></td>
<td class="tg-031e"></td>
<td class="tg-yw4l"></td>
<td class="tg-yw4l"></td>
</tr>
</table>

Here is an example, only total FootballPlayers
Step 1)
Add a class for FootballPlayers column when you add a row
Step 2)
Call total() javascript function while add a row and delete a row
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;" >Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l sum">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e total_fb_players"></td>
<td class="tg-031e total_summers"></td>
<td class="tg-yw4l total_bb_players"></td>
<td class="tg-yw4l total_sum"></td>
</tr>
</table>
<style>
#tg {border-collapse:collapse;border-spacing:0;}
#tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
#tg .tg-yw4l{vertical-align:top}
</style>
<script>
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled=true;
}
total();
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k=0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k=0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k=0;
}
var sum1 = (f1k+f2k+f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1=tbody.insertCell(0);
r1.innerHTML="";
var r2=tbody.insertCell(1);
r2.classList.add('fb_players')
r2.innerHTML=f1;
var r3=tbody.insertCell(2);
r3.classList.add('summers')
r3.innerHTML=f2;
var r4=tbody.insertCell(3);
r4.classList.add('bb_players')
r4.innerHTML=f3;
var r5=tbody.insertCell(4);
r5.classList.add('sum')
r5.innerHTML=sum1;
if(document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled=false;
}
total();
}
function total() {
var fb_players = document.getElementsByClassName("fb_players");
var total_fb_players = 0;
for(var i = 0; i < fb_players.length; i++) {
var v = parseInt(fb_players[i].innerHTML);
if (isNaN(v)) {
v=0;
}
console.log(v);
total_fb_players += v;
}
console.log(total_fb_players);
var total_fb_players_html = document.querySelector(".total_fb_players");
total_fb_players_html.innerHTML=total_fb_players;
}
</script>

Add classes to your cells and ids to for each total column in your table and execute as follows
Snippet below
function deleteRow() {
tg.deleteRow(1);
if (document.all("tg").rows.length == 2) {
document.getElementById("b").disabled = true;
}
}
function addRow() {
var f1 = document.getElementById("f1").value;
var f1k = parseInt(f1);
if (isNaN(f1k)) {
f1k = 0;
}
var f2 = document.getElementById("f2").value;
var f2k = parseInt(f2);
if (isNaN(f2k)) {
f2k = 0;
}
var f3 = document.getElementById("f3").value;
var f3k = parseInt(f3);
if (isNaN(f3k)) {
f3k = 0;
}
var sum1 = (f1k + f2k + f3k);
var row = document.createElement("TR")
var tbody = document.getElementById("tg").insertRow(1);
var r1 = tbody.insertCell(0);
r1.innerHTML = "";
var r2 = tbody.insertCell(1);
r2.innerHTML = f1;
r2.className = "football";
var r3 = tbody.insertCell(2);
r3.innerHTML = f2;
r3.className = "swimmer";
var r4 = tbody.insertCell(3);
r4.innerHTML = f3;
r4.className = "basketball";
var r4 = tbody.insertCell(4);
r4.innerHTML = sum1;
if (document.all("tg").rows.length >= 3) {
document.getElementById("b").disabled = false;
}
var football_el = document.getElementsByClassName("football");
var swim_count_el = document.getElementsByClassName("swimmer");
var basketball_el = document.getElementsByClassName("basketball");
var list = [football_el, swim_count_el, basketball_el];
grand_sum = 0;
for (var y = 0; y < list.length; ++y) {
var sum = 0;
for (var x = 0; x < list[y].length; ++x) {
sum += Number(list[y][x].innerHTML);
}
if (y == 0) {
document.getElementById("total_footballers").innerHTML = sum;
grand_sum += sum;
} else if (y == 1) {
document.getElementById("total_swimmers").innerHTML = sum;
grand_sum += sum;
} else if (y == 2) {
document.getElementById("total_basketballers").innerHTML = sum;
grand_sum += sum;
}
} //end for
document.getElementById("grandtotal").innerHTML = grand_sum;
}
#tg {
border-collapse: collapse;
border-spacing: 0;
}
#tg td {
font-family: Arial, sans-serif;
font-size: 14px;
padding: 10px 5px;
border-style: solid;
border-width: 1px;
overflow: hidden;
word-break: normal;
}
#tg th {
font-family: Arial, sans-serif;
font-size: 14px;
font-weight: normal;
padding: 10px 5px;
border-style: solid;
border-width: 1px;
overflow: hidden;
word-break: normal;
}
#tg .tg-yw4l {
vertical-align: top
}
<div class="row">
<label for="n">FootballPlayers: </label>
<input type="text" id="f1" />
</div>
<div class="row">
<label for="n">Swimmers: </label>
<input type="text" id="f2" />
</div>
<div class="row">
<label for="n">BasketballPlayers: </label>
<input type="text" id="f3" />
<button id="a" onClick="addRow();return false;">Add</button>
<button id="b" onClick="deleteRow();return false;">Delete</button>
</div>
<table id="tg">
<tr>
<th class="tg-031e"></th>
<th class="tg-031e">FootballPlayers</th>
<th class="tg-031e">Swimmers</th>
<th class="tg-yw4l">BasketballPlayers</th>
<th class="tg-yw4l">Sum</th>
</tr>
<tr>
<td class="tg-031e">Total</td>
<td class="tg-031e" id="total_footballers"></td>
<td class="tg-031e" id="total_swimmers"></td>
<td class="tg-yw4l" id="total_basketballers"></td>
<td class="tg-yw4l" id="grandtotal"></td>
</tr>
</table>

Related

Show calculated arithmetic mean in <td> when the button is clicked

please help me finish this, I'm getting nowhere.
what needs to be done
final results
I've explained in the pictures whats the finish goal.
This is a grade calculator.
There are 3 types of grades.. it should calculate the arithmetic mean for every category and arithmetic mean for all grades no matter which category they are.
Calculated values should be shown on the appropriate block, as shown in the picture.
input[type="number"]{
color : transparent;
text-shadow : 0 0 0 #000;
}
input[type="number"]:focus{
outline : none;
}
</style>
<body>
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Add grade</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick=""> Calculate </button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Written test</td>
<td style="width:70px; text-align: center;">Essay</td>
<td style="width:70px; text-align: center;">Class Activity</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all Writtentest, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all Essay, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all ClassActivity, inside td-->
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Arithmetic mean of all grades</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all numbers-->
</tr>
</tbody>
</table>
</div>
</body>
<script>
var ocena = 0;
var stranica = document.querySelector("#stranica")
function removeElement(obrisi) {
var dugme = obrisi.target;
stranica.removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max",5);
input.setAttribute("min",1);
var myParent = document.body;
//Create array of options to be added
var array = ["Written test","Essay","Class Activity"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
stranica.appendChild(item)
}
</script>```
var ocena = 0;
function removeElement(obrisi) {
var dugme = obrisi.target;
document.getElementById("stranica").removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max", 5);
input.setAttribute("min", 1);
var myParent = document.body;
//Create array of options to be added
var array = ["Kontrolni", "Vezbe", "Aktivnost"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
document.getElementById("stranica").appendChild(item)
}
function calcMean() {
var nameList=document.querySelectorAll('#stranica .item #mySelect');
var inputList=document.querySelectorAll('#stranica .item input');
var kontrolniList = [];
var vezbeList = [];
var aktivnostList = [];
var ocenaList = [];
for(var i=0; i< nameList.length; i++){
ocenaList.push(parseInt(inputList[i].value));
if(nameList[i].value=='Kontrolni') {
kontrolniList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Vezbe') {
vezbeList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Aktivnost') {
aktivnostList.push(parseInt(inputList[i].value));
}
}
document.getElementById("kontrolni").innerHTML=avg(kontrolniList);
document.getElementById("vezbe").innerHTML=avg(vezbeList);
document.getElementById("aktivnost").innerHTML=avg(aktivnostList);
document.getElementById("ocena").innerHTML=avg(ocenaList);
}
function avg( arr ) {
var total = 0, i;
for (i = 0; i < arr.length; i += 1) {
total += arr[i];
}
return total / arr.length;
}
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Dodaj ocenu</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick="javascript:calcMean();"> Izracunaj prosek</button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Kontrolni</td>
<td style="width:70px; text-align: center;">Vezbe</td>
<td style="width:70px; text-align: center;">Aktivnost</td>
</tr>
<tr>
<td id="kontrolni" style="text-align: center;"> </td>
<td id="vezbe" style="text-align: center;"></td>
<td id="aktivnost" style="text-align: center;"></td>
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Zakljucna ocena</td>
</tr>
<tr>
<td id="ocena" style="text-align: center;"> </td>
</tr>
</tbody>
</table>
</div>
Hope this will work.

how to print json object in my table?

I am trying to print my object that holds my inputName field and my inputDate field. I am successfully storing both variables onto my localStorage but I am unable to print it in my table. I am proving a picture to a better understanding. I tried to use console.log but It doesn't print anything in the console. I guess I do not know how to use console log.
What I am trying to do is the following : once an user inputs a name and date, I want to be able to display those values to my table.
function SortByKey(array,key){
return array.sort(function(a,b){
var x = a[key];
var y = b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
/* This function will save my input onto Local Storage*/
function getInput(){
var nameInput = document.getElementById('inputName').value;
localStorage.setItem('Name', nameInput);
var dateInput = document.getElementById( 'inputDate').value;
localStorage.setItem('Date', dateInput);
}
function SubmitInput() {
var JsObject =[];
var nameInput = document.getElementById('inputName').value;
var dateInput = document.getElementById('inputDate').value;
if (localStorage.getItem('datastorage')!=undefined) {
var JsObject = JSON.parse(localStorage.datastorage);
}
JsObject.push({'inputName':nameInput, 'inputDate':dateInput});
localStorage.setItem('datastorage',JSON.stringify(JsObject));
//console.log(JsObject);
print();
}
function print (){
var JsObject = JSON.parse(localStorage.getItem('datastorage'));
var clean = " ";
document.getELementByID('myTable').inner.HTML=clean;
for (var i = 0; I < JsObject.length; i++) {
document.getElementById('myTable').innerHTML += "<tr>" + "<td>" + JsObject[i].nameInput + "</td>" + "<td>" + JsObject[i].dateInput + "</td>" + "</tr>";
//console.log(JsObject);
}
}
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<table id="myTable" >
<tr>
<th>Name</th>
<th>Date</th>
<th>Endorsement</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<form class="form-horizontal">
<fieldset>
<legend>Endorse me</legend>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input onCLick ="getInput()" type="text" class="form-control" id="inputName" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Date</label>
<div class="col-lg-10">
<input onCLick="getInput()" type="text" class="form-control" id="inputDate" placeholder="Date">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button onClick="SubmitInput()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</fieldset>
</form>
</head>
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
</body>
</html>
Try This:
function SortByKey(array,key){
return array.sort(function(a,b){
var x = a[key];
var y = b[key];
return ((x<y)?-1:((x>y)?1:0));
});
}
/* This function will save my input onto Local Storage*/
function getInput(){
var nameInput = document.getElementById('inputName').value;
localStorage.setItem('Name', nameInput);
var dateInput = document.getElementById( 'inputDate').value;
localStorage.setItem('Date', dateInput);
}
function SubmitInput() {
var JsObject =[];
var nameInput = document.getElementById('inputName').value;
var dateInput = document.getElementById('inputDate').value;
if (localStorage.getItem('datastorage')!=undefined) {
var JsObject = JSON.parse(localStorage.datastorage);
}
JsObject.push({'inputName':nameInput, 'inputDate':dateInput});
localStorage.setItem('datastorage',JSON.stringify(JsObject));
//console.log(JsObject);
print();
}
function print (){
var JsObject = JSON.parse(localStorage.getItem('datastorage'));
var clean = " ";
document.getELementByID('myTable').inner.HTML=clean;
//for (var i = 0; I < JsObject.length; i++) {
/*
document.getElementById('myTable').innerHTML += "<tr>" + "<td>" + JsObject[i].nameInput + "</td>" + "<td>" + JsObject[i].dateInput + "</td>" + "</tr>"; */
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + JsObject[i].nameInput + "</td>");
tr.append("<td>" + JsObject[i].dateInput + "</td>");
tr.append("<td>" + next_variable + "</td>");
$('myTable').append(tr);
}
//console.log(JsObject);
}
<html>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<head>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> -->
</head>
<body>
<table id="myTable" >
</table>
<form class="form-horizontal">
<fieldset>
<legend>Endorse me</legend>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input onCLick ="getInput()" type="text" class="form-control" id="inputName" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Date</label>
<div class="col-lg-10">
<input onCLick="getInput()" type="text" class="form-control" id="inputDate" placeholder="Date">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button onClick="SubmitInput()" type="submit" class="btn btn-primary" >Submit</button>
</div>
</div>
</fieldset>
</form>
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
</html>

Calculating GPA and Credit Hours

<script type="text/javascript">
<!--Hide from old browsers
function gpacalc() {
var grade = new Array(9);
var credit = new Array(9);
var getGrade = new Array(5);
var getCredit = new Array(5);
var gradeCount = 12;
grade[0] = "A+";
credit[0] = 4;
grade[1] = "A";
credit[1] = 4;
grade[2] = "A-";
credit[2] = 3.7;
grade[3] = "B+";
credit[3] = 3.3;
grade[4] = "B";
credit[4] = 3;
grade[5] = "B-";
credit[5] = 2.7;
grade[6] = "C+";
credit[6] = 2;
grade[7] = "C-";
credit[7] = 1.7;
grade[8] = "D+";
credit[8] = 1.3;
grade[9] = "D";
credit[9] = 1;
grade[10] = "D-";
credit[10] = 0.7;
grade[11] = "F";
credit[11] = 0.0;
getGrade[0] = document.calcGpaForm.grade1.value;
getGrade[0] = getGrade[0].toUpperCase();
getGrade[1] = document.calcGpaForm.grade2.value;
getGrade[1] = getGrade[1].toUpperCase();
getGrade[2] = document.calcGpaForm.grade3.value;
getGrade[2] = getGrade[2].toUpperCase();
getGrade[3] = document.calcGpaForm.grade4.value;
getGrade[3] = getGrade[3].toUpperCase();
getGrade[4] = document.calcGpaForm.grade5.value;
getGrade[4] = getGrade[4].toUpperCase();
getGrade[5] = document.calcGpaForm.grade6.value;
getGrade[5] = getGrade[5].toUpperCase();
getCredit[0] = document.calcGpaForm.credit1.value;
getCredit[1] = document.calcGpaForm.credit2.value;
getCredit[2] = document.calcGpaForm.credit3.value;
getCredit[3] = document.calcGpaForm.credit4.value;
getCredit[4] = document.calcGpaForm.credit5.value;
getCredit[5] = document.calcGpaForm.credit6.value;
var totalGrades =0;
var totalCredits = 0;
var GPA = 0;
var i = 0;
for (i; i < 6; i++) {
if (getGrade[i] == "") {
break;
}
else if (getGrade[i] == "c" || getGrade[i] == "C") {
alert("'C' is not a vaild letter grade. Course " +eval(i + 1)+ ".")
return;
}
else if (isNaN(getCredit[i])) {
alert("Enter a vaild number of credits for Course " +eval(i + 1)+ ".")
return;
}
else if (getCredit[i] == "") {
alert ("You left the number of credits blank for Course " +eval(i + 1)+ ".")
return;
}
var validgradecheck = 0;
var x = 0;
for (x; x < gradeCount; x++) {
if (getGrade[i] == grade[x]) {
totalGrades = totalGrades + (parseInt(getCredit[i],10) * credit[x]);
totalCredits = totalCredits + parseInt(getCredit[i],10);
validgradecheck = 1;
break;
}
}
if (validgradecheck == 0) {
alert("Could not recognize the grade entered for Course " +eval(i + 1)+ ".");
return;
}
}
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
GPA = Math.round(( totalGrades / totalCredits ) * 100) / 100;
alert("GPA = " + eval(GPA));
return;
}
function copyRight() {
var lastModDate = document.lastModified;
var lastModDate = lastModDate.substring(0,10);
displayDateLast.innerHTML = "<h6>Copyright © Haiwook Choi. "+" <br /> This document was last modified "+lastModDate+".</h6>";
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
I'm trying to make a webpage that allows the user to enter from 4 to 6 grades for any course. Next to the letter grade, I'm wanting to put a text-field that accepts the credit hours for the courses. Also when the Calculate GPA button is clicked I want it to verify that a letter grade has been entered and then accumulate the grade points as well as the credit hours and display the GPA. I'm having trouble getting the GPA to calculate though. As well as having an alert display when a user enters anything other than a letter grade? Can someone look over my code and tell me what I should fix or add? Thanks if you read this and attempt to help!
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chapter 10 Cases and Places: 2</title>
<script type="text/javascript">
<!--Hide from old browsers
function gpacalc() {
var grade = new Array(9);
var credit = new Array(9);
var getGrade = new Array(5);
var getCredit = new Array(5);
var gradeCount = 12;
grade[0] = "A+";
credit[0] = 4;
grade[1] = "A";
credit[1] = 4;
grade[2] = "A-";
credit[2] = 3.7;
grade[3] = "B+";
credit[3] = 3.3;
grade[4] = "B";
credit[4] = 3;
grade[5] = "B-";
credit[5] = 2.7;
grade[6] = "C+";
credit[6] = 2;
grade[7] = "C-";
credit[7] = 1.7;
grade[8] = "D+";
credit[8] = 1.3;
grade[9] = "D";
credit[9] = 1;
grade[10] = "D-";
credit[10] = 0.7;
grade[11] = "F";
credit[11] = 0.0;
getGrade[0] = document.calcGpaForm.grade1.value;
getGrade[0] = getGrade[0].toUpperCase();
getGrade[1] = document.calcGpaForm.grade2.value;
getGrade[1] = getGrade[1].toUpperCase();
getGrade[2] = document.calcGpaForm.grade3.value;
getGrade[2] = getGrade[2].toUpperCase();
getGrade[3] = document.calcGpaForm.grade4.value;
getGrade[3] = getGrade[3].toUpperCase();
getGrade[4] = document.calcGpaForm.grade5.value;
getGrade[4] = getGrade[4].toUpperCase();
getGrade[5] = document.calcGpaForm.grade6.value;
getGrade[5] = getGrade[5].toUpperCase();
getCredit[0] = document.calcGpaForm.credit1.value;
getCredit[1] = document.calcGpaForm.credit2.value;
getCredit[2] = document.calcGpaForm.credit3.value;
getCredit[3] = document.calcGpaForm.credit4.value;
getCredit[4] = document.calcGpaForm.credit5.value;
getCredit[5] = document.calcGpaForm.credit6.value;
var totalGrades =0;
var totalCredits = 0;
var GPA = 0;
var i = 0;
for (i; i < 6; i++) {
if (getGrade[i] == "") {
break;
}
else if (getGrade[i] == "c" || getGrade[i] == "C") {
alert("'C' is not a vaild letter grade. Course " +eval(i + 1)+ ".")
return;
}
else if (isNaN(getCredit[i])) {
alert("Enter a vaild number of credits for Course " +eval(i + 1)+ ".")
return;
}
else if (getCredit[i] == "") {
alert ("You left the number of credits blank for Course " +eval(i + 1)+ ".")
return;
}
var validgradecheck = 0;
var x = 0;
for (x; x < gradeCount; x++) {
if (getGrade[i] == grade[x]) {
totalGrades = totalGrades + (parseInt(getCredit[i],10) * credit[x]);
totalCredits = totalCredits + parseInt(getCredit[i],10);
validgradecheck = 1;
break;
}
}
if (validgradecheck == 0) {
alert("Could not recognize the grade entered for Course " +eval(i + 1)+ ".");
return;
}
}
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
GPA = Math.round(( totalGrades / totalCredits ) * 100) / 100;
alert("GPA = " + eval(GPA));
return;
}
function copyRight() {
var lastModDate = document.lastModified;
var lastModDate = lastModDate.substring(0,10);
displayDateLast.innerHTML = "<h6>Copyright © Hannah. "+" <br /> This document was last modified "+lastModDate+".</h6>";
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
</head>
<body onLoad="gpacalc(); copyRight()">
<div class="center-div">
<p style="font-family:Arial, Helvetica, sans-serif; font-size:xx-large; font-weight:bold; text-align: center; color:blue">Calculating Your GPA</p>
<p class="block"><strong>Directions: </strong>Enter your letter grade for your courses. In the boxes to the right enter the credit hours per course. Then Click the Calculate GPA button to have your GPA calculated as well as your total credit hours.</p>
<form name="calcGpaForm" method="post">
<table>
<tr>
<h4 style="text-align: center">Letter Grade:</h4>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 1:
</th>
<td class="align-left"><input type="text" name="grade1" type="text" id="grade1" size="10" onBlur="validgradecheck" /></td>
<td class="margin-left: auto"><input type="text" name="credit1" id="credit1" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 2:
</th>
<td class="align-left"><input name="grade2" type="text" id="grade2" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit2" id="credit2" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 3:
</th>
<td class="align-left"><input name="grade3" type="text" id="grade3" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit3" id="credit3" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 4:
</th>
<td class="align-left"><input name="grade4" type="text" id="grade4" size="10" onBlur="validgradecheck" /> </td>
<td class="align-left"><input type="text" name="credit4" id="credit4" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 5:
</th>
<td class="align-left"><input type="text" name="grade5" id="grade5" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit5" id="credit5" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 6:
</th>
<td class="align-left"><input type="text" name="grade6" id="grade6" size="10" onBlur="validgradecheck"/></td>
<td class="align-left"><input type="text" name="credit6" id="credit6" size="10" /></td>
</tr>
<tr>
<td class="right-align">
<input name="button" type="button" value="Calculate GPA" onClick="gpacalc()"/>
</td>
<td class="align-left">
<input name="Reset" type="reset" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">GPA:</span>
</td>
<td><input type="text" name="gpacalc" id="gpacalc" value=" " size="10" /></td>
</tr>
</table>
</form>
</div>
<div id="displayDateLast">
</div>
</body>
</html>
Few remarks:
I don't think you need to worry about old browsers as no one should be using them nowadays. Therefore, <!--Hide from old browsers --> not needed.
What's the point of calculating the GPA when the page loads i.e. onload? There are no grades when the page loads up, so you'll always get an error. It is probably better to only calculate when the user clicks the button.
Do not repeat yourself.
Do not write for yourself to only read but for others, so comment your code.
Check this answer on the difference between dot notation and square brack notation when it comes to accessing an object property.
eval() is evil and not needed in your code.
Here's how I would do it (hopefully it answers all your questions):
// an object is a better data structure for storing grading scale
var gradingScale = {
'A+': 4,
'A': 4,
'A-': 3.7,
'B+': 3.3,
'B': 3,
'B-': 2.7,
'C+': 2.3,
'C-': 1.7,
'D+': 1.3,
'D': 1,
'D-': 0.7,
'F': 0.0
};
// note in JS, you can reference an element by their ID
// attaching onclick event handler to your button with ID "gpacalc"
gpacalc.onclick = function() {
var totalGradePoints = 0;
var totalCredits = 0;
// easier to just start at 1
for (var i = 1; i <= 6; i++) {
// you can access an object's property using [] notation; useful in this situation
// good idea to normalize your values e.g. trim, uppercase, etc
var grade = document.calcGpaForm['grade' + i].value.trim().toUpperCase();
var credit = document.calcGpaForm['credit' + i].value.trim();
// skip if no grade is entered
if (grade == "") {
break;
}
// check if grade is invalid i.e. not in the grading scale
if (!gradingScale.hasOwnProperty(grade)) {
alert("'" + grade + "' is not a valid letter grade. Course " + i + ".");
return;
// check if credit is empty
} else if (credit == "") {
alert("You left the number of credits blank for Course " + i + ".");
return;
// check if credit is not a number
} else if (isNaN(credit)) {
alert("Enter a valid number of credits for Course " + i + ".");
return;
}
// at this point, the grade and credit should both be valid...
credit = parseInt(credit, 10);
// so let's add them to the tally
totalGradePoints += gradingScale[grade] * credit;
totalCredits += credit;
}
// check if total credits is greater than zero
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
// show total
gpa.value = Math.round((totalGradePoints / totalCredits) * 10) / 10;
}
<form name="calcGpaForm" method="post">
<table>
<tr>
<h4 style="text-align: center">Letter Grade:</h4>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 1:
</th>
<td class="align-left"><input type="text" name="grade1" type="text" id="grade1" size="10"></td>
<td class="margin-left: auto"><input type="text" name="credit1" id="credit1" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 2:
</th>
<td class="align-left"><input name="grade2" type="text" id="grade2" size="10"></td>
<td class="align-left"><input type="text" name="credit2" id="credit2" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 3:
</th>
<td class="align-left"><input name="grade3" type="text" id="grade3" size="10"></td>
<td class="align-left"><input type="text" name="credit3" id="credit3" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 4:
</th>
<td class="align-left"><input name="grade4" type="text" id="grade4" size="10"></td>
<td class="align-left"><input type="text" name="credit4" id="credit4" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 5:
</th>
<td class="align-left"><input type="text" name="grade5" id="grade5" size="10"></td>
<td class="align-left"><input type="text" name="credit5" id="credit5" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 6:
</th>
<td class="align-left"><input type="text" name="grade6" id="grade6" size="10"></td>
<td class="align-left"><input type="text" name="credit6" id="credit6" size="10"></td>
</tr>
<tr>
<td class="right-align">
<input type="button" value="Calculate GPA" id="gpacalc">
</td>
<td class="align-left">
<input name="Reset" type="reset">
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">GPA:</span>
</td>
<td><input type="text" id="gpa" value="" size="10"></td>
</tr>
</table>
</form>
(Note: the sample attaches an onclick event handler to your button in the JS and not by using an onclick attribute. Though, the latter way should work.)

How to check the table whether the same roll number exists or not using javascript

Can we can check the roll number already exists or not.
with javascript
can we validate this
Showing with a alert message that the roll number exists if it is
already in the table
.
window.onload = function() {
document.getElementById('new').style.display = 'none';
};
function addtable(){
document.getElementById('new').style.display = 'block';
Rollno = document.getElementById("roll_number");
Name = document.getElementById("student_name");
Class = document.getElementById("class");
var Gender = null;
var inputElements = document.getElementsByClassName('gender');
for (var i = 0; inputElements[i]; ++i) {
if(inputElements[i].checked){
Gender = inputElements[i].value;
break;
}
};
Age = document.getElementById("age");
Phone = document.getElementById("phone_number");
var Result = null;
var inputElements = document.getElementsByClassName('result');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
Result = inputElements[i].value;
break;
}
};
var table = document.getElementById("new");
rowCount = table.rows.length;
row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= Rollno.value;
row.insertCell(1).innerHTML= Name.value;
row.insertCell(2).innerHTML= Class.value;
row.insertCell(3).innerHTML= Gender;
row.insertCell(4).innerHTML= Age.value;
row.insertCell(5).innerHTML= Phone.value;
row.insertCell(6).innerHTML= Result;
row.insertCell(7).innerHTML='<input type="submit" value = "Delete" onclick="deleteRow(this)">';
var roll = document.forms["student_detail"]["roll_number"].value;
if (roll == "") {
alert("Rollno must be filled out");
return false;
}
var name = document.forms["student_detail"]["student_name"].value;
if (name == ""){
alert("Name must be filled out");
return false;
}
var clas = document.forms["student_detail"]["class"].value;
if (clas == "") {
alert("select the class");
return false;
}
var age = document.forms["student_detail"]["age"].value;
if (age == ""){
alert("Age must be filled out");
return false;
}
var phone = document.forms["student_detail"]["phone_number"].value;
if (phone == "") {
alert("Phone number must be filled out");
return false;
}
if (document.student_detail.result1.checked == true && document.student_detail.result2.checked == true){
alert('Select any one result');
return false ;
}
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("new");
table.deleteRow(index);
}
function myFunction() {
var x = document.getElementById('myTable');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var change = document.getElementById("toggle");
if (change.innerHTML === "Hide Form")
{
change.innerHTML = "Show Form";
}
else {
change.innerHTML = "Hide Form";
}
}
function hideElem(){
document.getElementById('new').style.visibility = "hidden";
}
function showElem(){
document.getElementById('new').style.visibility = "visible";
}
.abc table{
width: 100%;
border-collapse: collapse;
}
.abc table th{
border: 1px solid #000;
}
.abc table td{
border: 1px solid #000;
}
h2{
color: black;
text-shadow: 2px 2px 8px #FF0000
}
input[type=text],select,input[type=number]{
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 2px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=button] {
width: 50%;
background-color: #4CAF50;
color: white;
padding: 14px 10px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=button]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<form name="student_detail" method="post" action="#" onsubmit="return addtable();">
<table id="myTable" >
<tr>
<td><h2>School Management Application</h2></td>
</tr>
<tr>
<td><label for="roll_number">Roll no</label></td>
<td><input type="text" id="roll_number" name="roll_number" placeholder="Roll Number"></td>
</tr>
<tr>
<td><label for="student_name">Student name</label></td>
<td><input type="text" id="student_name" name="student_name" placeholder="Student Name"></td>
</tr>
<tr>
<td><label for="class">Class</label></td>
<td><select name="class" id="class">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select></td>
</tr>
<tr>
<td><label>Gender</label></td>
<td><input type="radio" class="gender" name="gender" value="male">Male
<input type="radio" class="gender" name="gender" value="female">Female</td>
</tr>
<tr>
<td><label for="age">Age</label></td>
<td><input type="number" id="age" name="age" placeholder="Age"></td>
</tr>
<tr>
<td><label for="phone_number">Phone number</label></td>
<td><input type="text" id="phone_number" name="phone_number" placeholder="Phone Number"></td>
</tr>
<tr>
<td><label>Result</label></td>
<td><input type="checkbox" class="result" name="result1" value="passed" >Passed
<input type="checkbox" class="result" name="result2" value="failed" />Failed</td>
</tr>
<tr>
<td><input type="button" value="Submit" onclick="addtable()"></td>
</tr>
</table>
</form>
<table>
<tr>
<td><input type="button" value="Hide Form" id="toggle" onclick="myFunction()">
<input type="button" value="Hide table" id="tab" onclick="hideElem()">
<input type="button" value="Show table" id="tab1" onclick="showElem()"></td>
</tr>
</table>
<div class="abc">
<table id="new">
<tr>
<th>Rollno</th>
<th>Student name</th>
<th>Class</th>
<th>Gender</th>
<th>Age</th>
<th>Phone number</th>
<th>Result</th>
</tr>
</table>
</div>
Need to get alert if the same roll number enters again.After
submiting And a alert message to be shown
Can any one help me to do this
Here's a function that checks for duplicates
checkDupes($("#someId"));
function checkDupes(itemArray) {
var isdupe = false;
for (var i = itemArray.length - 1; i >= 0; i--) {
var value = itemArray[i].value;
if (value == null || value == '' || value.trim().length == 0) {
itemArray[i].style.backgroundColor = 'red';
} else {
if (i > 0) {
for (var j = i - 1; j > -1 && i > 0; j--) {
if (value.trim().toLowerCase() == itemArray[j].value.trim().toLowerCase()) {
itemArray[i].style.backgroundColor = 'red';
isdupe = true;
}
}
if (!isdupe) {
itemArray[i].style.backgroundColor = 'transparent';
}
}
}
}
}

JavaScript - Traversing the HTML DOM using childNodes causes errors in Non IE browsers

I have the following table being rendered in my browser. It's generated from the server side.
<table id="tblQuestions" class="tblQuestionsContainer" border="0">
<tr>
<td id="1" class="tdQuestion">Are u an indian citizen ?</td>
</tr><tr>
<td><table id="answer-1" border="0">
<tr>
<td><input id="answer-1_0" type="radio" name="answer-1" value="1" /><label for="answer-1_0">Yes</label></td><td><input id="answer-1_1" type="radio" name="answer-1" value="0" /><label for="answer-1_1">No</label></td>
</tr>
</table></td>
</tr><tr>
<td id="2" class="tdQuestion">Do you have a passport ?</td>
</tr><tr>
<td><table id="answer-2" border="0">
<tr>
<td><input id="answer-2_0" type="radio" name="answer-2" value="1" /><label for="answer-2_0">Yes</label></td><td><input id="answer-2_1" type="radio" name="answer-2" value="0" /><label for="answer-2_1">No</label></td>
</tr>
</table></td>
</tr>
</table>
Now I am using the following code in my JavaScript to validate the radio button's checked state.
var tblQuestionBoard=document.getElementById("tblQuestions");
tblAnswer = tblQuestionBoard.rows[1].childNodes[0].childNodes[0]
Now tblAnswer should be an object having the Table with id "answer-1"
In IE, I am getting it. But in Mozilla and rest of the browsers I am getting it as undefined.
How to solve this?
It's because you're using childNodes and whitespaces in the DOM are considered to be text nodes by Firefox et. al but not IE
See this answer for an explanation
My suggestions
1.Set up some wrapper functions that ignore any nodeType other than 1 (ELEMENT_NODE) to do DOM traversing. Something like
function child(elem, index) {
// if index is not supplied, default is 1
// you might be more comfortable making this 0-based
// in which case change i initial assignment value to 0 too
index = index || 1;
// get first child element node of elem
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
// use the index to move to nth-child element node
for(var i=1; i < index;i++) {
(function() {
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
and use like so - Working Demo - (Code at the bottom of the answer for reference)
<table id="myTable">
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>
<script type="text/javascript">
child(document.getElementById('myTable'), 2); // will get the tbody
</script>
2.Use getElementbyId(), getElementsByTagName() or getElementsByName() instead of relying on position in the DOM
3.Use a JavaScript library that abstracts away browser differences (jQuery comes highly recommended)
The Demo Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('getCellContents').onclick = getCellContents;
}
function child(elem, index) {
index = index || 1;
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
for(var i=1; i < index;i++) {
(function() {
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function getCellContents() {
var row = parseInt(document.getElementById('row').value, 10);
var column = parseInt(document.getElementById('column').value, 10);
var result;
var color;
var table = document.getElementById('table');
var cells = table.getElementsByTagName('td');
for (var i= 0; i < cells.length; i++) {
(function() {
cells[i].bgColor = '#ffffff';
})();
}
if (row && column) {
var tbody = child(table , 2);
var selectedRow = (row <= tbody.getElementsByTagName("tr").length)? child(tbody, row): null;
var selectedCell = (selectedRow && column <= selectedRow.getElementsByTagName("td").length)? child(selectedRow, column): null;
if (selectedRow && selectedCell) {
selectedCell.bgColor = '#00ff00';
result = selectedCell.innerHTML;
color = '#b7b7b7';
}
else {
result = 'Cell does not exist';
color = '#ff0000';
}
}
else {
result = 'You must provide numeric arguments for Row and Column Number';
color = '#ff0000';
}
var results = document.getElementById('results');
results.innerHTML = result;
results.style.color = color;
}
</script>
<title>DOM Traversal</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
font-family: Verdana, Helvetica, Arial;
font-size: 0.8em;
}
h2 {
text-align:center;
}
table {
border: 1px solid #000;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
padding: 2px;
}
fieldset {
border: 0;
}
label {
display: block;
width: 120px;
text-align: right;
float: left;
padding-right: 10px;
margin: 5px 0;
}
input {
margin: 5px 0;
}
input.text {
padding: 0 0 0 3px;
width: 172px;
}
input.button {
margin: 15px 0 0 130px;
}
span {
font-weight: bold;
color: #b7b7b7;
}
</style>
</head>
<body>
<h2>Example to demonstrate use of JavaScript DOM traversing wrapper functions</h2>
<div style="margin: 0 auto; width: 600px;">
<fieldset>
<label for="row">Row Number:</label><input id="row" class="text" type="text" /><br/>
<label for="column">Column Number:</label><input id="column" class="text" type="text" /><br/>
<input id="getCellContents" type="button" class="button" value="Get Cell Contents" />
</fieldset>
<p>Results: <span id="results"></span></p>
<table id="table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Banana</td>
<td>Apple</td>
<td>Orange</td>
<td>Pineapple</td>
<td>Cranberry</td>
</tr>
<tr>
<td>Monkey</td>
<td>Giraffe</td>
<td>Elephant</td>
<td>Tiger</td>
<td>Snake</td>
</tr>
<tr>
<td>C#</td>
<td>Java</td>
<td>Python</td>
<td>Ruby</td>
<td>Haskell</td>
</tr>
<tr>
<td>France</td>
<td>Spain</td>
<td>Italy</td>
<td>Germany</td>
<td>Netherlands</td>
</tr>
</tbody>
</table>
<p style="font-weight:bold;">The Code:
<pre><code>
<script type="text/javascript">
window.onload = function() {
document.getElementById('getCellContents').onclick = getCellContents;
}
function child(elem, index) {
index = index || 1;
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
for(var i=1; i < index;i++) {
(function() {
if(elem)
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function getCellContents() {
var row = parseInt(document.getElementById('row').value, 10);
var column = parseInt(document.getElementById('column').value, 10);
var result;
var color;
var table = document.getElementById('table');
var cells = table.getElementsByTagName('td');
for (var i= 0; i < cells.length; i++) {
(function() {
cells[i].bgColor = '#ffffff';
})();
}
if (row && column) {
var tbody = child(table , 2);
var selectedRow = (row <= tbody.getElementsByTagName("tr").length)?
child(tbody, row): null;
var selectedCell = (selectedRow && column <= selectedRow.getElementsByTagName("td").length)?
child(selectedRow, column): null;
if (selectedRow && selectedCell) {
selectedCell.bgColor = '#00ff00';
result = selectedCell.innerHTML;
color = '#b7b7b7';
}
else {
result = 'Cell does not exist';
color = '#ff0000';
}
}
else {
result = 'You must provide numeric arguments for Row and Column Number';
color = '#ff0000';
}
var results = document.getElementById('results');
results.innerHTML = result;
results.style.color = color;
}
</script>
</code>
</pre>
</p>
</div>
</body>
</html>

Categories