How to compare numerical values of two innerHTML elements? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to compare the numerical values of elements in Javascript (Still learning, so I am grateful for any help).
Currently I have the code:
if (parseInt(document.getElementById("player1").innerHTML) > parseInt(document.getElementById("player2").innerHTML)) {
document.getElementById("gametitle").innerHTML = "Player 1 wins!"
} else if (parseInt(document.getElementById("player2").innerHTML) > parseInt(document.getElementById("player1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "Player 2 wins!"
} else if (parseInt(document.getElementById("player1").innerHTML) > parseInt(document.getElementById("computer1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You win!"
} else if (parseInt(document.getElementById("player1").innerHTML) > parseInt(document.getElementById("computer2").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You win!"
} else if (parseInt(document.getElementById("player1").innerHTML) > parseInt(document.getElementById("computer3").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You win!"
} else if (parseInt(document.getElementById("computer1").innerHTML) > parseInt(document.getElementById("player1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You lose!"
} else if (parseInt(document.getElementById("computer2").innerHTML) > parseInt(document.getElementById("player1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You lose!"
} else if (parseInt(document.getElementById("computer3").innerHTML) > parseInt(document.getElementById("player1").innerHTML)) {
document.getElementById("gametitle").innerHTML = "You lose!"
} else {
document.getElementById("gametitle").innerHTML = "There's an error!"
}
Any help would be greatly appreciated.

The issue here is that you are using the innerHTML when you should be using innerText. See Difference between innerText and innerHTML in javascript
Also, since you mentioned you are new to programming, here are some best practices for you.
If you are going to be comparing the values multiple times you should save the value in a variable instead of constantly using the resources to retrieve the same value.
var player1 = parseInt(document.getElementById("player1").innerText)
var player2 = parseInt(document.getElementById("player2").innerText)
var player3 = parseInt(document.getElementById("player3").innerText)
var computer1 = parseInt(document.getElementById("computer1").innerText)
var computer2 = parseInt(document.getElementById("computer2").innerText)
var computer3 = parseInt(document.getElementById("computer3").innerText)
You are also comparing multiple scores using the same logic so instead of repeating this code you should write a function. A function is a block of code that you can name and call later, see here for more information: http://www.w3schools.com/js/js_functions.asp
function compareScores(playerScore,computerScore){
if (playerScore > computerScore){
document.getElementById("gametitle").innerText = "You win!"
} else if (computerScore > playerScore){
document.getElementById("gametitle").innerText = "You lose!"
} else {
document.getElementById("gametitle").innerText = "You Tied!"
}
}
Now you just need to call this function with the values for each set.
compareScores(player1,computer1)
compareScores(player2,computer2)
compareScores(player3,computer3)

Don't use innerHTLM, as it returns... HTML. parseInt won't work on that. Use innerText instead:
if (parseInt(document.getElementById("computer3").innerText) > parseInt(document.getElementById("player1").innerText)) {
// Do something
}
Also, it will help you a lot if you first extract the values, then compare them:
var computer3Score = parseInt(document.getElementById("computer3").innerText);
var player1Score = parseInt(document.getElementById("player1").innerText);
if (computer3Score > player1Score) {
// do something
}

Relying on the DOM to store the data is a bad practice. What if you want to use the same logic and data with a different view ? You would have to refactor the entire code. Rather do the opposite, generate the DOM based on a data structure that is the unique source of data for all your application. Thus, you don't need the DOM to manage the data anymore.
In the example below, the data source is an array called "players". Try to add a new player to the array and see how easier it is to manage. Moreover, if you want to change the HTML of the score board, you just have to edit the template once for all players. This template is located in the function called "dataToHtml".
var players, tbody, button, indexOf;
players = [
{ name: "John", score: 2 },
{ name: "Mary", score: 1 },
{ name: "Bot 1", score: 4 },
{ name: "Bot 2", score: 3 }
];
indexOf = Array.prototype.indexOf;
button = document.getElementsByTagName("button")[0];
tbody = document.getElementsByTagName("tbody")[0];
tbody.innerHTML = dataToHtml();
button.onclick = function () {
var i, best, trs;
best = bestScore();
trs = tbody.childNodes;
for (i = 0; i < trs.length; i++) {
trs[i].style.backgroundColor = (
players[i].score == best ? "yellow" : "white"
);
}
};
tbody.onclick = function (ev) {
var i, tr, score, name;
tr = ev.target.parentNode;
i = indexOf.call(this.childNodes, tr);
name = players[i].name;
score = prompt("New score for " + name + " :");
if (!isNaN(score = parseInt(score, 10))) {
tr.childNodes[1].textContent = score;
players[i].score = score;
}
};
function bestScore () {
var i, best;
for (i = 0; i < players.length; i++) {
if (i == 0 || players[i].score > best) {
best = players[i].score;
}
}
return best;
}
function dataToHtml () {
var i, html = "";
for (i = 0; i < players.length; i++) {
html += ""
+ "<tr>"
+ "<td>" + players[i].name + "</td>"
+ "<td class=\"score\">" + players[i].score + "</td>"
+ "</tr>";
}
return html;
}
body, button {
font: normal 12px Arial;
}
div {
display: inline-block;
vertical-align: middle;
text-align: center;
}
table {
margin-right: 1em;
}
table, th, td {
border-collapse: collapse;
border: 1px solid #999;
padding: .25em;
}
td.score {
text-align: right;
}
<div>
<table>
<thead>
<tr>
<th>player</th>
<th>score</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div><div>
<p><button type="button">Who wins ?</button></p>
<p>click a row<br />to change<br />the score</p>
</div>

Related

Want to remove previously appended table

When I Click on submit button after clicking on the links it appends perfectly but when I hit the button again it doesn't remove previously appended table.
I want to clear the previously created table when user clicks on the cross button and then print the table again or else overwrite the table but instead it is not removing the table and prints a new one.Image Part OneImage Part TwoImage Part ThreeImage Part Four
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(" + i + ")'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
}
//To Remove The Specific Element User Want To Delete
function remove(id) {
orders_list.splice(id, id);
loop("t");
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>
Update your remove function as function remove(el) { el.closest('table').remove(); }.
Update parameter in html as "</td><td onclick='remove(this)'>×</td></tr>".
And add orders_list = []; in the end of loop function.
Try it below.
//variables
var order1 = document.getElementById('one').innerText;
var order2 = document.getElementById('two').innerText;
var order3 = document.getElementById('three').innerText;
var order4 = document.getElementById('four').innerText;
var temp = 0;
var orders_list = []; //Array
//Object Orientation To Create Order And Then Add It In Array
function orders(name) {
this.name = name;
if (orders_list[temp] == null) {
orders_list.push(name);
}
temp++;
}
//Main Function Which Creates Orders
function order_maker(order_name) {
var order = new orders("." + order_name);
}
//To Append Child Each Time Submit Buton Is Pressed And Check the Loop
function loop(argument) {
var i = 0;
while (i < orders_list.length) {
var temporary = document.createElement("table");
var orders_temp_list = orders_list[i];
temporary.innerHTML = "<tr><td>" + orders_list[i] + "</td><td onclick='remove(this)'>×</td></tr>";
document.body.appendChild(temporary);
//This Block Is That I was Checking
if (argument == "f") {
temporary.innerHTML = " ";
}
if (argument == "t") {
console.log("Done");
}
i++;
}
orders_list = [];
}
//To Remove The Specific Element User Want To Delete
function remove(el) {
el.closest('table').remove();
}
a {
margin: 20px;
padding: 30px;
}
table {
border: 3px solid #242424;
}
tr,
td {
padding: 20px;
}
<!DOCTYPE html>
<head></head>
<body>
Cake1
Cake2
Cake3
Cake4
<form>
<input placeholder="name">
<input placeholder="email">
<input placeholder="order">
</form>
<p id="para"></p>
<button onclick="loop('t')">Click</button>
</body>

I was practicing a way to loop numbers to create a times table but the loop only runs one time

I am practicing creating a function that loops whatever number I put into the input into a times table. I used a for loop to achieve this but I ran into an issue. My for loop only runs one time and it only get my input * 10 for some reason. Can someone please help. Thank you.
function myFunction() {
var inputNumber = document.querySelector(".input-field").value;
inputNumber = parseInt(inputNumber);
if (isNaN(inputNumber) || inputNumber == "" || inputNumber == null) {
document.querySelector(".output h1").innerHTML = "Please enter a number!";
} else {
for (i = 1; i <= 10; i++) {
let product = inputNumber * i;
document.querySelector(".output").innerHTML = "<br>" + inputNumber + " * " + i + " = " + product + "<br>";
}
}
}
Looks like you update the HTML on every iteration. However, I think you want to expand the innerHTML to include all elements?
I would look into creating html elements in javascripts and adding them in html like this (draft, untested):
const element = document.createElement("div")
for (let i = 1; i < 10; i++) {
let product = inputNumer * i;
element.appendChild(document.createTextNode(`${inputNumer} ${product}`);
}
Please study this. It is using recommended event listener and a map
const arr = [...Array(11).keys()].slice(1); // numbers from 1 to 10
const h1 = document.querySelector("#output h1"),
result = document.getElementById("result"),
inputField = document.getElementById("inputField");
inputField.addEventListener("input", function() {
const inputNumber = +this.value;
console.log(inputNumber)
h1.classList.toggle("hide", inputNumber); // keep hide if ok number
result.innerHTML = inputNumber ? arr.map(i => `${inputNumber} * ${i} = ${inputNumber*i}`).join(`<br/>`) : "";
});
.hide {
display: none;
}
<input type="number" id="inputField" class=".input-field" />
<hr/>
<div id="output">
<h1 class="error hide">Please enter a number!</h1>
<div id="result">
</div>
</div>

Writing data into table with unknown number of rows

I am in a very basic "Intro to JS" course and my solving of this problem needs to equally basic and antiquated.
The exercise is supposed to display a table with a header with student names & scores of those scoring 90 or more. (Data is drawn from another js file.)
It then is supposed to display the total number of students and the total number of students scoring 90 or more. My math & if statement seem to be working, but the display is not...by a long shot. Any help would be greatly appreciated.
const ZERO = 0;
const NINETY_PERCENT = 90;
var studentName;
var studentScore;
var totalStudents;
var totalStudentsWithAs;
var studentRecords;
studentRecords = openStudentExamRecords();
function initializeExamRecords() {
totalStudents = ZERO;
totalStudentsWithAs = ZERO;
}
function startTable() {
document.write("<th>Student Name</th>");
document.write("<th>Exam Score</th>");
}
function printRecords() {
initializeExamRecords();
startTable();
while (studentRecords.readNextRecord()) {
studentName = studentRecords.getStudentName();
studentScore = studentRecords.getStudentScore();
totalStudents++;
if (studentScore >= NINETY_PERCENT) {
document.write("</td><td>");
document.write(studentName);
document.write("</td><td>");
document.write(studentScore);
totalStudentsWithAs++;
totalStudents = Number(totalStudents);
totalStudentsWithAs = Number(totalStudentsWithAs); alert("");
}
}
}
function endTable() {
document.write("</td></tr>");
}
function printTotals() {
printRecords();
document.write("</td><td>");
document.write("<tr><td colspan='5'> </td></tr>");
document.write("<tr><td colspan='5'>Total Students: <strong>" +
totalStudents + "</strong></td></tr>");
document.write("<tr><td colspan='5'>Total Sudents with A's: <strong>" +
totalStudentsWithAs + "</strong></td></tr>");
document.write("</td><tr>");
}
function endTable() {
document.write("</td></tr>");
}
printTotals();
endTable();

How to move group of items up and down in ng-repeat [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am using ng-repeat to show the items in ui in angular js and i need to move the
Items up and down in the ng-repeat table from external button.
i am able to move the items up and down but there is one more
condition in which i need to move group of items example:
id reportname comments
1 report1 na
2 report2 test
2 report4 test
3 report3 test
3 report3 na
4 report4 test
I need to move the enitre group of 3,3 above 2,2 or move entire 2,2 below 3,3.
Can someone please let me know how can we do that?
Here is a complete working solution, using Lodash for a bunch of utility methods.
EDIT: Rewrote and refactored to cater for cases where not all items with same id are grouped together. This now only moves adjacent items with the same id, not all items with the same id in the array.
angular.module('stackoverflow', []).controller('MainCtrl', function($scope) {
$scope.data = [{
id: 1,
reportname: 'report1',
comments: 'na'
}, {
id: 2,
reportname: 'report2',
comments: 'test'
}, {
id: 2,
reportname: 'report4',
comments: 'test'
}, {
id: 3,
reportname: 'report3',
comments: 'test'
}, {
id: 3,
reportname: 'report3',
comments: 'na'
}, {
id: 4,
reportname: 'report4',
comments: 'test'
}];
$scope.moveGroup = function(item, dir) {
dir = normalizeDir(dir);
firstIndexOfGroup
var firstIndexOfGroup = findFirstIndexWithSameId(item);
var endIndexOfGroup = findEndIndexOfGroup(firstIndexOfGroup, item);
var itemsInGroup = $scope.data.slice(firstIndexOfGroup, endIndexOfGroup + 1);
var idToSwapWith = ($scope.data[firstIndexOfGroup - 1] || {}).id;
// if moving down, swap with first entry past group end
if (dir === 'down') {
idToSwapWith = ($scope.data[endIndexOfGroup + 1] || {}).id;
}
if (idToSwapWith > 0) {
// remove from current position
$scope.data.splice(firstIndexOfGroup, _.size(itemsInGroup));
// insert group of items with same id at correct index
var firstItemWithPrevIdIndex = _.findIndex($scope.data, 'id', idToSwapWith);
if (dir === 'down') {
firstItemWithPrevIdIndex = _.findLastIndex($scope.data, 'id', idToSwapWith) + 1;
}
var spliceArgs = [firstItemWithPrevIdIndex, 0].concat(itemsInGroup);
$scope.data.splice.apply($scope.data, spliceArgs);
}
};
$scope.moveItem = function(item, dir) {
var index = $scope.data.indexOf(item);
if (normalizeDir(dir) === 'up') {
$scope.data.splice(index - 1, 2, item, $scope.data[index - 1]);
} else {
$scope.data.splice(index, 2, $scope.data[index + 1], item);
}
}
function normalizeDir(dir) {
switch ((dir || '').toString().toLowerCase()) {
case 'up':
case 'u':
return 'up';
}
return 'down';
}
function findFirstIndexWithSameId(item) {
var index = $scope.data.indexOf(item);
for (var i = index - 1; i >= 0; i--) {
if ($scope.data[i].id !== item.id) {
break;
} else {
index = i;
}
}
return index;
}
function findEndIndexOfGroup(startIndexOfGroup, item) {
var index = startIndexOfGroup;
for (var i = startIndexOfGroup + 1, len = _.size($scope.data); i < len; i++) {
if ($scope.data[i].id === item.id) {
index = i;
} else {
break;
}
}
return index;
}
});
.move-link-btn {
font-size: smaller;
color: lightblue;
padding: 2px 5px;
}
.move-link-btn:hover {
text-decoration: underline;
cursor: pointer;
}
td,
th {
outline: 1px solid #cfcfcf;
padding: 2px 5px;
font-family: sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.8.0/lodash.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="stackoverflow" ng-controller="MainCtrl">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Comments</th>
<th>Move Commands</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in data">
<td>{{item.id}}</td>
<td>{{item.reportname}}</td>
<td>{{item.comments}}</td>
<td>
<a class="move-link-btn" ng-click="moveItem(item, 'up')">Item Up</a>
<a class="move-link-btn" ng-click="moveItem(item, 'down')">Item Down</a>
<a class="move-link-btn" ng-click="moveGroup(item, 'up')">Group Up</a>
<a class="move-link-btn" ng-click="moveGroup(item, 'down')">Group Down</a>
</td>
</tr>
</tbody>
</table>
</div>
I create small demo for up and down element in ng-repeat http://plnkr.co/edit/mBoIY5ZCCQA4sRSVHuQB?p=preview
Please see this and review it.
In above demo add
<input type="button" name="changeOrder" ng-click="changeReportOrder()" value="Change Order">
<div ng-repeat="report in reports | orderBy:predicate:reverce">{{report.id}} {{report.reportname}} {{report.comments}}</div>
in body tag and
$scope.reports = [
{id:1,reportname:'report1',comments:'na'},
{id:2,reportname:'report2',comments:'test'},
{id:2,reportname:'report4',comments:'test'},
{id:3,reportname:'report3',comments:'test'},
{id:3,reportname:'report3',comments:'na'},
{id:4,reportname:'report4',comments:'test'}
];
$scope.predicate = '-id';
$scope.changeReportOrder = function(){
if($scope.predicate == 'id')
$scope.predicate = '-id';
else
$scope.predicate = 'id';
}
In controller. and order change ascending/descending of reports base on id when click on Order Change button.

Using DOM for first time to change color of unanswered questions in form onSubmit

Here is my form:
<form id="Test" action="index.php?course=4" method="post" name="Test" onSubmit="IsFormComplete(12)">
Inside the form is a table dynamically generated with id=Qx class=Qx where x is 1 through 12:
<tr id="Q2" class="Q2">
<td width="5%">2) </td>
<td colspan="2">According to the Institute of Medicine study the number of deaths from medical errors per year is between</td>
Here is my javascript function:
function IsFormComplete(iQuestions) {
var questionNum = iQuestions;
itemOkay=true;
for (var i=1;i<questionNum;i++) {
for (var j=0;j<4;j++) {
var thisItem = eval("document.Test.Q" + i + "[" + j + "].checked");
if (!thisItem) {
itemOkay = false;
document.getElementById(eval("Q" + i)).style.color = "red";
}
}
}
alert("item okay = " + itemOkay);
if (itemOkay) {
return true;
} else {
return false;
}
}
Not working PLEASE help. New to DOM and have tried various tags:
document.getElementById(eval("Q" + i)).style.color = "red";
document.Test.getElementById(eval("Q" + i)).style.color = "red";
document.getElementById("Q1").style.color = "red"; //To try literal instead of variable
etc.
You don't need the eval. getElementById uses a string. Try this:
document.getElementById("Q"+i).style.color = "red";

Categories

Resources