Javascript for loop not repeating strings - javascript

very new to Javascript here, and I think I'm having a logic issue. So basically for class I'm building a hangman game, and I am having trouble with double letters. for instance if the word is food, when I enter an "O" it will pass through the for loop, hit that first O, push it to the screen, and stop dead in its tracks. I can do whatever I want to that first "O" but a second one or any other repeated letter gets ignored. Now the alert I wrote directly under the start of the for() loop, will successfully print both "O's", as will logging it to the console, or even flat out writing document.write(splitWord[m]);
So to me, I think it has to be my if statement. I could be 100% wrong on this, but I assume that the if statement tells it to see the first "O", do what's in the bracket, and then move on to the next letter skipping any doubles. If I am right about this, what would be a better option to keep the loop going, so both "O's" would be filled. And if I am completely wrong, what would be a better course of action to accomplish this task. Any help would be very greatly appreciated.
Thanks
var remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var removedLetters =[];
var wordList = ["django", "the#good#the#bad#and#the#ugly", "a#fistful#of#dollars","for#a#few#dollars#more","once#upon#a#time#in#the#west","the#wild#bunch","pale#rider"];
var titleList =["django", "The Good The Bad And The Ugly", "A Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"];
var songList =["Jango", "The Good The Bad And The Ugly", "Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"]
var selectedWord;
console.log(selectedWord);
var livesRemaining = 12;
var score = 0;
var wordWorth = 0;
var wins = 0;
var losses = 0;
var gameOn = false;
function chooseAWord(){
selectedWord = wordList[Math.floor(Math.random() * wordList.length)];
console.log(selectedWord);
}
function printWord(){
document.getElementById("wordDisplayer").innerHTML = selectedWord;
}
function buildTiles(){
// create a new div element
// and give it some content
var splitWord = selectedWord.split("");
for(i = 0; i < splitWord.length; i++){
if (splitWord[i] != '#'){
// var newTile = document.createElement("div");
//var newContent = document.createTextNode("");
//newTile.appendChild(newContent); //add the text node to the newly created div.
document.getElementById("wordTiles").innerHTML += '<div class="tileStyle" id="' + splitWord[i] + '"></div>';
wordWorth++;
// add the newly created element and its content into the DOM
//var currentDiv = document.getElementById("wordTiles");
//currentDiv.appendChild(newTile, currentDiv);
// newTile.setAttribute("class", "tileStyle");
}else if(splitWord[i] == '#'){
var blankTile = document.createElement("div");
var spaceContent = document.createTextNode("");
blankTile.appendChild(spaceContent);
document.getElementById("wordTiles").innerHTML += '<div class="blankStyle" id="' + splitWord[i] + '"></div>';
}
}
}
function clearTiles(){
var myNode = document.getElementById("wordTiles");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
function refreshAlphabet(){
remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
displayAvailableLetters();
}
function keyPressed(){
checkPlayerChoiceNew();
}
var playerGuess = document.onkeyup = function myKeyDown(event){
playerGuess = event.key;
if(gameOn==true){
keyPressed();
}else{
}
}
function checkPlayerGuess(){
document.getElementById("isThisWorking").innerHTML = playerGuess;
}
// function myFunction() {
// var str = "Tha bast things in lifa ara free";
// var patt = new RegExp(playerGuess);
// var res = patt.test(selectedWord.toLowerCase());
// document.getElementById("demo").innerHTML = res;
//}
function displayAvailableLetters(){
document.getElementById("lettersStillAvailable").innerHTML = remainingLetters;
console.log(remainingLetters);
}
function displayRemovedLetters(){
document.getElementById("lettersUsed").innerHTML = removedLetters;
}
function updateScore(){
document.getElementById("scoreTotal").innerHTML = score;
}
function updateWins(){
document.getElementById("winTotals").innerHTML = wins;
}
function updateLosses(){
document.getElementById("lossTotals").innerHTML = losses;
}
function checkScore(){
if(score == selectedWord.length && livesRemaining > 0){
document.getElementById("gameOver").innerHTML = "WINNER! Congratulations!!!";
wins++;
updateWins();
gameOn=false;
}else if (livesRemaining == 0){
livesRemaining == -1;
document.getElementById("gameOver").innerHTML = "You have failed!";
losses++;
updateLosses();
gameOn=false;
}else{
document.getElementById("gameOver").innerHTML = "Good Luck!";
}
}
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = playerGuess;
}
}
}
//check playerGuess against selectedWord
function checkPlayerChoice(){
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
if(compareWord == true && compareAlphabet == true ){
document.getElementById("demo").innerHTML = playerGuess;
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
displayAvailableLetters();
displayRemovedLetters();
score++;
updateScore();
checkScore();
}else if(compareWord == true && compareAlphabet == false){
document.getElementById("demo").innerHTML = "Already tried that one";
}else if(compareWord == false && compareAlphabet == true){
livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
document.getElementById("demo").innerHTML = "Already tried that one ;)";
}else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
}else{
/*livesRemaining--;
document.getElementById("lives").innerHTML = livesRemaining;
removedLetters.push(playerGuess.toLowerCase());
updateScore();
checkScore();
displayAvailableLetters();
displayRemovedLetters();*/
document.getElementById("demo").innerHTML = "Not a Valid Key";
}
}
//document.onkeyup = function myKeyDown(event){
// playerGuess = event.key;
//}
//start / Restart the game
function resetGame() {
livesRemaining = 12;
score =0;
wordWorth = 0;
clearTiles();
document.getElementById("lives").innerHTML = livesRemaining;
chooseAWord();
printWord();
buildTiles();
refreshAlphabet();
gameOn=true;
}
.tileStyle{
width:30px;
height:30px;
border:1px solid black;
background-color:green;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.blankStyle{
width:30px;
height:30px;
background-color:orange;
float:left;
margin-left:10px;
margin-right:10px;
margin-bottom:10px;
margin-top:10px;
}
.fixer{
width:100%;
height:10px;
clear:both;
}
<body>
<button onclick="checkPlayerChoice()">Try it</button>
<p id="demo"></p>
<p> lives: </p>
<p id = "lives"> 0</p>
<p> Score: </p>
<p id = "scoreTotal">0</p>
<p>wins</p>
<p id ="winTotals">0</p>
<p>losses</p>
<p id ="lossTotals">0</p>
<p id ="gameOver"></p>
<button onclick ="resetGame()">New Game</button>
<p>Here is the word</p>
<p id = "wordDisplayer">Press New Game to Start</p>
<div id = "wordTiles"></div>
<div class ="fixer"></div>
<button onclick ="checkPlayerGuess()">What Key was Pressed?</button>
<p id ="isThisWorking">What will I say?</p>
<p>Letters Still Available</p>
<p id ="lettersStillAvailable"></p>
<p>Bad Guesses</p>
<p id ="lettersUsed"></p>
<br />
selectedWord ="food";
function checkPlayerChoiceNew(){
var splitWord = selectedWord.split("");
var choice = new RegExp(playerGuess);
var compareWord = choice.test(selectedWord.toLowerCase());
var compareAlphabet = choice.test(remainingLetters);
var compareRemovedList = choice.test(removedLetters);
for (m = 0; m < splitWord.length; m++){
//alert(splitWord[m]);
if(playerGuess == splitWord[m]){
document.getElementById(splitWord[m]).innerHTML = choice;
}
}
}

You can refer this below logic. In this example, I have given some inputs.
var selectedWord ="food";
var displayString = [];
for(var i = 0; i < selectedWord.length; i++){
displayString[i] = "-"
}
var outputEle = document.getElementById("output");
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
function checkPlayerChoiceNew(playerGuess){
var newWord = "";
var regExp = new RegExp(playerGuess,'ig')
selectedWord.replace(regExp, function(value, index){
displayString[index] = value;
return value;
});
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
newWord = displayString.join("");
if(selectedWord == newWord){ alert("You Won the game"); }
//outputEle.innerText = displayString.join(" ");
}
checkPlayerChoiceNew('o');
checkPlayerChoiceNew('g');
checkPlayerChoiceNew('d');
checkPlayerChoiceNew('f');
<div id="output">
</div>

Related

How to decrement each click of the animation

I am trying to create animation game. Animation game must consits of One image alternating with another every half a second. I am intended to count++ on each click of the happy-face fish and count-- on each sad-face fish clicked. But, my code is only incrementing, whatever the image is clicked. Also,my code shows me two different images while It must have to be only one.
I have to count a click while my animation is running ( animation: images should be alternating every half a second. It will look like fish is smiling for half second and then crying for another half second then repeats). If i click on happy face, I will score 1 and if click on sad-face I will lose 1. In the end it must show you win if i achieve 10 and resets again on clicking Start Animation.
[Output should be like this:][1]
var image = "happy";
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
fish_img = document.getElementById("happy_fish");
f_img = document.getElementById("happy_fish");
fish_img.classList.add('on');
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
if (image == "happy") {
image = "sad";
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
} else {
image = "happy";
fish_img.src =
"https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
}
}
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="" id="sad_fish" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
I modified your StartAnimation and animationfunction methods to make the fish dissapear with a toggle instead of trying to modify the source of the image.
I made it with a css class off which will make a fish dissapear with display: none;
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
var initialWords = document.getElementById("d");
initialWords.innerHTML = "Your Score: <span id=\"score\">0</span>";
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
var fish_img = document.getElementById("happy_fish");
var f_img = document.getElementById("sad_fish");
fish_img.classList.toggle('off');
f_img.classList.toggle('off');
}
.off {
display: none;
}
<button onClick="StartAnimation()">Start Animation</button>
<br>
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="happy" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="sad" id="sad_fish" class="off" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
You can make things a lot simpler by having one img element and one click handler.
In the snippet I merged the two click handlers into one and added a check for the state of the fish (being represented now by the boolean isHappy).
I attached this handler to a single img element in your HTML and in the animation function I alternate its src attribute between the happy and sad fish according to the isHappy state.
Additionally, Since the counter and the total score are the same, I use only the total score variable.
var isHappy = true;
var totalscore;
var Schedule;
function clickFish() {
if (isHappy) {
totalscore++;
} else {
totalscore--;
}
var scoreSpan = document.getElementById("score");
scoreSpan.innerHTML = totalscore;
if (totalscore === 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + totalscore + " Game Over. You Win!";
}
}
function StartAnimation() {
isHappy = true
totalscore = 0;
clearInterval(Schedule);
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
fish_img = document.getElementById("fish");
isHappy = !isHappy;
if (isHappy) {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
} else {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
}
}
<button onclick="StartAnimation()">Start animation</button><br />
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="fish" onClick="clickFish()">
<br>
<h1 id="d">
Your Score:
<span id="score">0</span>
</h1>

Javascript: Loop items in array

For my website I need a function with questions and answers in loop.
After the last question the first question should come again.
I have found something but the loop does not work, it is certainly simple but I do not get that.
<!DOCTYPE html>
<html>
<body>
<div>
<div id="question" onclick="changeText()">
Start Quiz
</div>
<div id="answer" onclick="nextQuestion()">
are you ready?
</div>
</div>
<script type="text/javascript">
var details = "Question 1ans:Answer 1qst:Question 2ans:Answer 2qst:Question 3ans:Answer 3qst:Question 4ans:Answer 4qst:Question 5ans:Answer 5qst:Question 6ans:Answer 6qst:Question 7ans:Answer 7qst:Question 8ans:Answer 8qst:Question 9ans:Answer 9qst:Question 10ans:Answer 10";
var questionList = details.split("qst:");
var div = document.getElementById('question');
var ans = document.getElementById('answer');
function changeText(){
if (div.style.display !== 'none') {
div.style.display = 'none';
ans.style.display = 'block';
}
else {
div.style.display = 'block';
ans.style.display = 'none';
}
}
function nextQuestion(){
div.style.display = 'block';
ans.style.display = 'none';
var max = questionList.length;
if(max > 0){
var num = 0;
var qst = questionList[num].split("ans:");
div.innerHTML =qst[0];
ans.innerHTML = qst[1];
questionList.splice(num,1);}
else {
}
}
</script>
</body>
</html>
You must reset value of n every time reach to max so you must put n in outer scope in global variable scope and don't splice questionList because you want to iterate over that array again after reaching to end of it:
var details = "Question 1ans:Answer 1qst:Question 2ans:Answer 2qst:Question 3ans:Answer 3qst:Question 4ans:Answer 4qst:Question 5ans:Answer 5qst:Question 6ans:Answer 6qst:Question 7ans:Answer 7qst:Question 8ans:Answer 8qst:Question 9ans:Answer 9qst:Question 10ans:Answer 10";
var questionList = details.split("qst:");
var div = document.getElementById('question');
var ans = document.getElementById('answer');
//Variable n must declare here
var num = 0;
function changeText() {
if (div.style.display !== 'none') {
div.style.display = 'none';
ans.style.display = 'block';
} else {
div.style.display = 'block';
ans.style.display = 'none';
}
}
function nextQuestion() {
div.style.display = 'block';
ans.style.display = 'none';
var max = questionList.length;
if (max > 0) {
var qst = questionList[num].split("ans:");
div.innerHTML = qst[0];
ans.innerHTML = qst[1];
//there is no need to splice questionList
//questionList.splice(num, 1);
num++;
//Check for num to not to be greater than questionList.length
if (num >= max)
num = 0;
} else {
}
}
<div id="question" onclick="changeText()">
Start Quiz
</div>
<div id="answer" onclick="nextQuestion()">
are you ready?
</div>

what's wrong with this javascript script.?

I am trying to learn javascript by following this exercise from MDN website Learn JavaScript
here is my final code for the game.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Number guessing game</title>
<style>
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
.lastResult {
color: white;
padding: 3px;
}
</style>
</head>
<body>
<h1>Number guessing game</h1>
<p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or less. We'll tell you if your guess was too high or too low.</p>
<div class="form">
<label for="guessField">Enter a guess:</label>
<input type="text" id="guessField" class="guessField" autofocus>
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</body>
<script>
// Your JavaScript goes here
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector(".guesses");
var lastResult = document.querySelector(".lastResult");
var lowOrHi = document.querySelector(".lowOrHi");
var guessField = document.querySelector(".guessField");
var guessSubmit = document.querySelector(".guessSubmit");
var test; //used for creating new reset button
var count = 1; // counter for counting user input
function checkGuess() {
//alert('checkGuess is called');
var value = Number(guessField.value);
if (count === 1) {
guesses.textContent = "Previous guesses :"
}
guesses.textContent += value + ' ';
if (value === randomNumber) {
lastResult.textContent = "congratulation u successfully guessed the number";
lastResult.style.backgroundColor = "green";
lowOrHi.textContent = "";
left = 1;
setGameOver();
} else if (count === 10) {
lastResult.textContent = "game over"
lastResult.style.backgroundColor = "red";
left = 1;
setGameOver();
} else {
lastResult.textContent = "WRONG";
lastResult.style.backgroundColor = "red";
if (value < randomNumber) {
lowOrHi.textContent = "too low";
} else {
lowOrHi.textContent = "too high";
}
}
count++;
guessField.value = '';
}
guessSubmit.addEventListener("click", checkGuess);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
test = document.createElement('button');
test.textContent = "restart game";
document.body.appendChild(test);
test.addEventListener('click', resetGame);
}
function resetGame() {
count = 1;
var resetParas = document.querySelectorAll('.resultParas');
for (var i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
test.parentNode.removeChild(test);
}
</script>
</html>
But when i try to run the game and use the reset game button to restart the game then i am not able to manipulate guesses,lastResult and lowOrHi elements using textContent and backgroundColor properties.
Your blanking out everything inside .resultParas.. And this will include all you <p> tags. IOW: after doing that they have disappeared from the DOM, you can see this say in chrome inspector that .resultPara's after clicking reset game is now blank, and all your p tags have gone.
I think what you really want to do, is blank out the children (the p tags)..
You don't need querySelectorAll either, as in your case there is only the one.
var resetParas = document.querySelector('.resultParas');
for(var i = 0 ; i < resetParas.children.length ; i++) {
resetParas.children[i].textContent = '';
}

Highlight Keywords in a given text area based on list of words

I need some help to get my program running. Its been a week and I have only made such little progress with youtube videos and google search.
I want to design a simple web application like the on on this website http://text2data.org/Demo.
With some help i was able to find the following javascript from http://www.the-art-of-web.com/javascript/search-highlight/#withutf8 that i could modify.
I have developed how i want my interface to look like but i am stuck at achieving the primary objective of keyword highlighting.
I have therefore turned to the only community i know best to help me get through this so as to make the dead line by Monday.
MODIFIED JAVA CODE ADOPTED FROM CHIRP
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function Hilitor(id, tag)
{
var targetNode = document.getElementById(id) || document.getElementById(SentenceIn);
var hiliteTag = tag || "EM";
var skipTags = new RegExp("^(?:" + hiliteTag + "|SCRIPT|FORM|SPAN)$");
var colors = ["#ff6", "#a0ffff", "#9f9", "#f99", "#f6f"];
var wordColor = [];
var colorIdx = 0;
var matchRegex = "";
var openLeft = false;
var openRight = false;
this.setMatchType = function(type)
{
switch(type)
{
case "left":
this.openLeft = false;
this.openRight = true;
break;
case "right":
this.openLeft = true;
this.openRight = false;
break;
case "open":
this.openLeft = this.openRight = true;
break;
default:
this.openLeft = this.openRight = false;
}
};
this.setRegex = function(input)
{
input = input.replace(/^[^\w]+|[^\w]+$/g, "").replace(/[^\w'-]+/g, "|");
var re = "(" + input + ")";
if(!this.openLeft) re = "\\b" + re;
if(!this.openRight) re = re + "\\b";
matchRegex = new RegExp(re, "i");
};
this.getRegex = function()
{
var retval = matchRegex.toString();
retval = retval.replace(/(^\/(\\b)?|\(|\)|(\\b)?\/i$)/g, "");
retval = retval.replace(/\|/g, " ");
return retval;
};
// recursively apply word highlighting
this.hiliteWords = function(node)
{
if(node === undefined || !node) return;
if(!matchRegex) return;
if(skipTags.test(node.nodeName)) return;
if(node.hasChildNodes()) {
for(var i=0; i < node.childNodes.length; i++)
this.hiliteWords(node.childNodes[i]);
}
if(node.nodeType == 3) { // NODE_TEXT
if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) {
if(!wordColor[regs[0].toLowerCase()]) {
wordColor[regs[0].toLowerCase()] = colors[colorIdx++ % colors.length];
}
var match = document.createElement(hiliteTag);
match.appendChild(document.createTextNode(regs[0]));
match.style.backgroundColor = wordColor[regs[0].toLowerCase()];
match.style.fontStyle = "inherit";
match.style.color = "#000";
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
}
};
};
// remove highlighting
this.remove = function()
{
var arr = document.getElementsByTagName(hiliteTag);
while(arr.length && (el = arr[0])) {
var parent = el.parentNode;
parent.replaceChild(el.firstChild, el);
parent.normalize();
}
};
// start highlighting at target node
this.apply = function(input)
{
this.remove();
if(input === undefined || !input) return;
this.setRegex(input);
this.hiliteWords(targetNode);
};
}
MY HTML PAGE
#model DataAnalyzer.Models.EnterSentence
#{
ViewBag.Title = "Data Analysis";
}
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
</hgroup>
</div>
</section>
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Enter Sentence</title>
<script type="text/javascript" src="~/Scripts/hilitor.js"></script>
<script type="text/javascript">
function dohighlight() {
var myHilitor = new Hilitor("SentenceIn");
myHilitor.apply("badWords");
//Variable for output text
var enteredText = document.getElementById("SentenceIn").value;
//Hide analyze button
document.getElementById("highlight").style.display = 'none';
//show result text area
document.getElementById("result").style.display = 'block';
//display text in results text area
document.getElementById("result").innerHTML = myHilitor;
}
</script>
</head>
<body>
<div>
<p>
Welcome to Data Analysis, Please enter a sentence in the textbox below.
</p>
#using (Html.BeginForm())
{
<div id="sentenceOut" style=" height:auto; width:500px">
#Html.TextArea("SentenceIn")
</div>
<input id="highlight" type="button" value="Analyze" onclick="dohighlight();" /> <br />
<div id="result" style="display:none; background-color:#ffffff; float:left; min-height:200px; width:500px;">
I am some text from the box up there
</div>
<div id="goodWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
Good excelent bravo awesome splendid magnificent sweet estatic plaudible love like
</div>
<div id="neutralWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
lukewarm maybe meh suppose
</div>
<div id="badWords" style=" background-color:#ffffff; min-height:200px; width:500px;">
fuck shit evil damn cock bullshit hate dislike poor
</div>
<script type="text/javascript">
document.getElementById("goodWords").style.visibility = 'hidden';
document.getElementById("neutralWords").style.visibility = 'hidden';
document.getElementById("badWords").style.visibility = 'hidden';
</script>
}
</div>
</body>
</html>

Calculating a student grade in JavaScript

I've got an HTMl form to input student names and grades in which should use JavaScript to calculate a grade that is then printed on the screen. My HTMl works fine if I comment the meat of my JavaScript out, but not if I don't. The error is somewhere in the code that I commented out, but I just can't find it (or them).
The HTML form will submit, alert the user, and show my message correctly as long as it is fed a concrete grade and score instead of trying to fetch it through getGrade() and getScore(). This is why I know the bug is in the JavaScript.
I've run the page in the JavaScript console to look for bugs, but there are no red flag errors.
This is my first HTML/JavaScript program, and I not very good at it. Anyway, it's a day late and in less than two hours, it will be two days late, so if anyone could help, I'd appreciate it hugely. Here's the code, sorry if it's too much:
<!DOCTYPE html>
<html>
<head>
<title>Joe Peterson's Assignment 7</title>
<script>
function calculateGrade(){
document.getElementById("form1").style.display = "none";
document.getElementById("p1").style.display = "block";
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
/*
var s1 = new Student(fname, lname);
for (var i = 0; i < classworkArray.length; i++)
s1.addGradedActivity(classworkArray[i]);
for (var i = 0; i < homeworkArray.length; i++)
s1.addGradedHomework(homeworkArray[i]);
s1.setMidterm(valMidterm, lMidterm);
s1.setFinal(valFinal, lFinal);
var grade = s1.getGrade();
var score = s1.getScore();
*/
document.getElementById("span1").innerHTML = (grade);
document.getElementById("span2").innerHTML = (score);
document.getElementById("fname").innerHTML = (fname);
document.getElementById("lname").innerHTML = (lname);
alert(document.getElementById("FirstName").value);
return false;
}
/*
function Coursework(){
var sum = 0;
var num = 0;
this.addScore = function(score){
if (score < 0) {score = 0;}
if (score > 100) {score = 100;}
sum += score;
num++;
}
this.getAverage = function(){
return (sum/num);
}
}
function Exam(){
var score = 0;
var grade = "";
this.Exam = function(Score, Grade)
{
if (Score < 0) {Score = 0;}
if (Score > 100) {Score = 100;}
score = Score;
if (Grade != "A" && Grade != "B" && Grade !="C"
&& Grade !="D" && Grade != "F")
{
console.log("You have submitted a bad grade for an Exam, value of:G.");
Grade = "F";
}
grade = Grade;
}
this.getScore = function(){
return score;
}
this.getGrade = function(){
return grade;
}
}
function Student(){
var firstName;
var lastName;
var midterm;
var finalExam;
var homework = new Coursework();
var inclass = new Coursework();
this.Student = function(first, last){
firstName = first;
lastName = last;
}
this.setMidterm = function(score, grade){
midterm = new Exam(score, grade);
}
this.setFinal = function(score, grade){
finalExam = new Exam(score, grade);
}
this.addGradedHomework = function(score){
homework.addScore(score);
}
this.addGradedActivity = function(score){
inclass.addScore(score);
}
this.getFinalGrade = function(totalScore)
{
var grade = totalGrade(totalScore);
var grade2 = "F";
var midGrade = this.convertGrade(midterm.getGrade());
var finGrade = this.convertGrade(finalExam.getGrade());
if (midGrade < finGrade)
{
grade2 = midterm.getGrade();
}
else
{
grade2 = finalExam.getGrade();
}
if (convertGrade(grade) > convertGrade(grade2))
return(grade);
else
return(grade2);
}
this.totalGrade = function(totalScore)
{
var totalGrade = "F";
if (totalScore >= 90)
totalGrade = "A";
else if (totalScore >= 80)
totalGrade = "B";
else if (totalScore >= 70)
totalGrade = "C";
else if (totalScore >= 60)
totalGrade = "D";
else
totalGrade = "F";
return (totalGrade);
}
this.convertGrade = function(letter)
{
var num = 0;
if (letter === "A")
num = 4;
else if (letter === "B")
num = 3;
else if (letter === "C")
num = 2;
else if (letter === "D")
num = 1;
else
num = 0;
return(num);
}
this.getScore = function()
{
var totalScore = 0;
totalScore += inclass.getAverage() * .15;
totalScore += homework.getAverage() * .25;
totalScore += midterm.getScore() * .25;
totalScore += finalExam.getScore() * .35;
return totalScore;
}
this.getGrade = function()
{
var totalScore = 0;
totalScore += inclass.getAverage() * .15;
totalScore += homework.getAverage() * .25;
totalScore += midterm.getScore() * .25;
totalScore += finalExam.getScore() * .35;
var grade = getFinalGrade(totalScore);
return grade;
}
}
*/
</script>
</head>
<body>
<p><h1>Joe Peterson's Assignment 7</h1></p>
<form name="input" id="form1" onsubmit="return calculateGrade()" style="display:form">
First name: <input type="text" name="FirstName" id="FirstName" value="Joe"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Peterson"><br>
Homework Scores (separate with commas): <input type="text" name="HomeworkScores" id="HomeworkScores" value="90, 80, 98"><br>
Activity Scores (separate with commas): <input type="text" name="ActivityScores" id="ActivityScores" value="71, 65, 96"><br>
Midterm Exam Percentage: <input type="text" name="MidtermScore" id="MidtermScore" value="91"><br>
Midterm Exam Letter Grade: <input type="text" name="MidtermLetter" id="MidtermLetter" value="A"><br>
Final Exam Percentage: <input type="text" name="FinalScore" id="FinalScore" value="75"><br>
Final Exam Letter Grade: <input type="text" name="FinalLetter" id="FinalLetter" value="C"><br>
<input type="submit" value="Submit">
</form>
<p id="p1" style="display:none">Final course grade for <span id="fname">Joe</span> <span id="lname">Peterson</span> is: <span id="span1">X</span> (<span id="span2">yy</span>%)</p>
</body>
</html>

Categories

Resources