display H1 only after prompt answer is correct Javascript - javascript

I need Happy Birthday to display only after a user puts the right input in prompt (which is 30). I want it to be hidden by default.
The reason I am doing it this way is that I want to add some CSS animation to this h1 tag later.
function myFunction() {
var txt;
var myTextbox = document.getElementById("bday");
var Age = prompt("How old are you?:");
if (Age == 30) {
return myTextbox;
} else {
txt = "Really? ";
}
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="demo"></h1>
<h2 id="bday"> Happy Birthday! </h2>

You need to add hidden attribute to element with id = "bday"
document.getElementById("bday").style.display = "none";
function myFunction() {
var txt;
var myTextbox = document.getElementById("bday");
var Age = prompt("How old are you?:");
if (Age == 30) {
document.getElementById("bday").style.display = "block";
return myTextbox;
} else {
txt = "Really? ";
}
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="demo"></h1>
<h2 id="bday" hidden> Happy Birthday! </h2>

No need to complicate, you can do it with less markup and improved functionality:
function myFunction() {
var myTextbox = document.getElementById("response");
var Age = prompt("How old are you?");
if (Age == 30) {
myTextbox.innerHTML = "Happy Birthday!";
} else if (Age == null) { // addition, if clicked on cancel
myTextbox.innerHTML = "";
} else {
myTextbox.innerHTML = "Really?";
}
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="response"></h1>

Related

Can't get button to show up on click with javascript visibility

I'm having trouble working with my next button on my webpage. I can get the other parts of the page (the answer message) to show up fine with when the button is clicked, but for some reason it will not work with this next button. Hiding it works fine, but when I click the button the next button will not show up. If I don't hide or style = "none", the button shows up fine. I've tried .style = "none" & .style = "block" and .visibility = "hidden" and .visibility = "visible", with no success. If anyone could give me some insight I'd appreciate it!
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky() {
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
} else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next() {
};
<div class="user-response">
What is <input type="text" id="user_answer"> ?
<button onclick="clicky()" type=b utton>Submit</button>
<button onclick="next()" type=s ubmit id="next">Next -></button>
</div>
<p id="correct">{{clue.answer}}</p>
<p id="score">{{score}}</p>
<p id="value">{{clue.worth}}</p>
<form method="GET">
<input type="hidden" name="score_get" value=0>
</form>
<div class="answer" id="answer">
</div>
At the end of the clicky function you are trying to set the innerHTML of a missing element "showed_score", It results with an error and quit the function before it is done.
Just remove this line or add the element to your html
I created this interactive snippet. Looks like there is an error (Uncaught TypeError: Cannot read property 'innerHTML' of null) happening right above that is throwing console errors. Based on your code the elements showed_score and score_get do not exist. Fixing this will hopefully fix your original problem.
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id = "next">Next -></button>
</div>
<p id = "correct"></p>
<p id = "score"></p>
<p id = "value"></p>
<form method = "GET">
<input type = "hidden" name = "score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
<script type = "text/javascript">
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next(){
};
</script>
I don't know what template engine youre using to render {{clue.answer}} but I imagine there's an answer in there somewhere. Try the following code instead (you were missing an id reference for getElementById :
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id = "next">Next -></button>
</div>
<p id = "correct">{{clue.answer}}</p>
<p id = "score">{{score}}</p>
<p id = "value">{{clue.worth}}</p>
<form method = "GET">
<input type = "hidden" name = "score_get" id="score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>
<div id="showed_score">
</div>
<script type = "text/javascript">
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
var correct = document.getElementById("correct").innerHTML;
var score = document.getElementById("score").innerHTML;
var value = document.getElementById("value").innerHTML;
var val2 = value.substring(1);
var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
score -= worth;
}
document.getElementById("showed_score").innerHTML = "Score is now $" + Math.floor(score);
document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
}
function next(){
}
</script>
Try commenting these 2 lines:
document.getElementById("showed_score").innerHTML = "Score is now $" + score;
document.getElementById("score_get").value = score;
They trigger an error which prevents the button from becoming visible.
You probably have an error before it gets to the code for visibility.
Look in your console to find errors and what is causing it.
Here's your example with most of it commented out and it works:
document.getElementById("correct").style.display = "none";
document.getElementById("score").style.display = "none";
document.getElementById("value").style.display = "none";
document.getElementById("next").style.visibility = "hidden";
function clicky(){
var user_answer = document.getElementById("user_answer").value;
//var correct = document.getElementById("correct").innerHTML;
//var score = document.getElementById("score").innerHTML;
//var value = document.getElementById("value").innerHTML;
//var val2 = value.substring(1);
//var worth = parseInt(val2);
if (user_answer == correct) {
document.getElementById("answer").innerHTML = "Correct!";
score += worth;
}
else {
//document.getElementById("answer").innerHTML = "Sorry, the answer is actually " + correct + " not " + user_answer;
//score -= worth;
}
//document.getElementById("showed_score").innerHTML = "Score is now $" + score;
//document.getElementById("score_get").value = score;
document.getElementById("next").style.visibility = "visible";
};
function next(){
};
<div class = "user-response">
What is <input type = "text" id = "user_answer"> ?
<button onclick = "clicky()" type = button>Submit</button>
<button onclick = "next()" type = submit id="next">Next -></button>
</div>
<p id = "correct">{{clue.answer}}</p>
<p id = "score">{{score}}</p>
<p id = "value">{{clue.worth}}</p>
<form method = "GET">
<input type = "hidden" name = "score_get" value = 0>
</form>
<div class = "answer" id = "answer">
</div>

Math Quiz Counter

Recently I have been making a math quiz for fun. However, I have tried to come up with a counter to count up the user's correct answers, and display the count at the bottom of the page. I have tried looking up this before but have found nothing.
Here is my HTML:
<div>
<p>What is 18 + 4?</p>
<div>
<input type="text" id="lol">
<button id="q1" onclick="lmao()">Answer</button>
</div>
<p id="q1c" class="correct"></p>
<p id="q1i" class="incorrect"></p>
<p>What is 19 + 21?</p>
<div>
<input type="text" id="loll">
<button id="q2" onclick="lmfao()">Answer</button>
</div>
<p id="q2c" class="correct"></p>
<p id="q2i" class="incorrect"></p>
</div>
Here is my JavaScript:
function lmao() {
if (document.getElementById("lol").value == "22") {
document.getElementById("q1c").innerHTML = "Correct!";
alert('Correct');
} else {
document.getElementById("q1i").innerHTML = "Incorrect!";
alert('Incorrect');
}
}
function lmfao() {
if (document.getElementById("loll").value == "40") {
document.getElementById("q2c").innerHTML = "Correct!";
alert('Correct');
} else {
document.getElementById("q2i").innerHTML = "Incorrect!";
alert('Incorrect');
}
}
Instead of using separate <p> tags for marking if the answers are incorrect or correct, you can simplify it down to one <p> tag with different id's, and just update the text inside them, and then we use the simple JavaScript notation to update the color of the font: object.style.color = "green". This provides much cleaner HTML.
Here is a working example (I stripped out all the excess tags and styles):
var answer1Count = 0;
var answer2Count = 0;
var correctCount = 0;
function answer1() {
var answer = document.getElementById("problem1");
var alert = document.getElementById("problem1Alert");
if (answer.value == "22") {
alert.textContent = "Correct!";
alert.style.color = "green";
correctCount +=1; //update global count of correct answers
answer1Count +=1;
document.getElementById("correctCount").textContent = correctCount;
} else {
if (answer1Count !== 0) {
answer1Count -=1;
correctCount -=1;
document.getElementById("correctCount").textContent = correctCount;
}
alert.textContent = "Incorrect!";
alert.style.color = "Red";
}
}
function answer2() {
var answer = document.getElementById("problem2");
var alert = document.getElementById("problem2Alert");
if (answer.value == "40") {
alert.textContent = "Correct!";
alert.style.color = "green";
answer2Count +=1; //update global count of correct answers
correctCount +=1;
document.getElementById("correctCount").textContent = correctCount;
} else {
if (answer2Count !== 0) {
answer2Count -=1;
correctCount -= 1;
document.getElementById("correctCount").textContent = correctCount;
}
alert.textContent = "Incorrect!";
alert.style.color = "Red";
}
}
<p>What is 18 + 4?</p>
<input type="text" id="problem1">
<button onclick="answer1()">Answer</button>
<p id="problem1Alert"></p>
<p>What is 19 + 21?</p>
<input type="text" id="problem2">
<button onclick="answer2()">Answer</button>
<p id="problem2Alert"></p>
<p>Correct Answer Count: <b id="correctCount">0</b></p>
Instead of using innerHTML, we use textContent it is safer and faster for updating with pure text because it does not have to parse for HTML. You can easily search around SO for the disadvantages of using innerHTML.
In addition, I would avoid inline styling with CSS at all costs. It makes your code much harder to read. I recommend putting all your styles in a separate stylesheet and just including that style sheet inside your <head> tag like so:
<link rel="stylesheet" href="style.css">

Javascript for loop not repeating strings

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>

Javascript: Taking values from a textbox and adding it to the divs

So I have been racking my brain on how to add the a different value from the text box to a different div. So div1 gets the first thing the user typed, div2 gets the second, div3 gets the third, and so on. Everytime a user presses the "Add" button whatever the user typed will be added to one of the Div's above it. Right now I have it to where by pressing "Add" the value of the textbox is put in the first div. How do I create a function that will allow the user to add values to other divs. I assume you need a for loop but I do not know how to tackle it.
Here is my code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<div id="colorme" style = "cursor:pointer" onClick= "highlightLink()"><p id = "doubleStuff" ondblclick = "dubleStuff()">check this out</p></div>
<div id="colorme2" style = "cursor:pointer" onClick= "highlightLink2()"><p id = "doubleStuff2" ondblclick = "dubleStuff2()">check this out</p></div>
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick = "workInfoAdd()">Add</button>
<script>
function highlightLink(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'red';
highL2.style.backgroundColor = 'transparent';
};
function highlightLink2(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'transparent';
highL2.style.backgroundColor = 'red';
};
function dubleStuff(){
var x = "You double clicked it";
document.getElementById('putstuff').innerHTML = x;
};
function dubleStuff2(){
var x = "different stuff";
document.getElementById('putstuff').innerHTML = x;
};
function workInfoAdd(){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {
z.value = "";
}
};
</script>
</body>
</html>
Would something like this work.
var i = document.getElementById('addingInfo');
for(i = 0; i < 4; i++){
document.getElementbyId('workInfo').value = i //or some other variable that specifies the "adding info"
Any assistance would be greatly appreciated. As stated above after everytime the user presses ADD, the value they put into the text box will be added to the subsequent div. First add goes to first div, second goes to second div and so on.
You should probably write something like this:
var divIndex = 0;
function workInfoAdd() {
var z = document.getElementById('workInfo');
var p = document.getElementById('addingInfo' + (divIndex || ''));
if (!p) {
return;
}
if (z.value === null || z.value === "") {
alert('please enter work info');
} else {
p.innerHTML = z.value;
z.value = "";
}
divIndex++;
};
<div id="workInfo1" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo"></p>
</div>
<div id="workInfo12" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo1"></p>
</div>
<div id="workInfo13" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo2"></p>
</div>
<div id="workInfo14" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo3"></p>
</div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type="button" name="addWorkInfo" id="addWorkInfo" onclick="workInfoAdd()">Add</button>
Additionally you can use document.querySelector() for more advanced matching of elements ex.
var p = document.querySelector('.workInfo' + divIndex + ' > p.addingInfo' + divIndex);
Try the below code but remember that this solution should be used if you are going to limit the number of div (i.e only 3 or 4 divs) because if you want unlimited divs you will have to program an if-else statement for each possible div:
// Declare variable
var x = 0;
function workInfoAdd(){
// Increment
x++
// Check increment value
if(x == 1){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else { z.value = "";}
}
// Check increment value
else if(x == 2){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo1').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
// Check increment value
else if(x == 3){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo2').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
}
https://jsfiddle.net/6byvuzxf/
I have created check points as mentioned in my comment before.
Hope this helps.
See if this is what you want. I have added a class for all the p tags which will contain the information after click.
Html
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick ="workInfoAdd()">Add</button>
javascript
function workInfoAdd()
{
var elements = document.getElementsByClassName('addingInfo');
for(i=0;i<elements.length;i++)
{
if(elements[i].innerHTML == "")
{
elements[i].innerHTML = document.getElementById('workInfo').value;
document.getElementById('workInfo').value = "";
return;
}
}
}
http://jsfiddle.net/okLme061/1/

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>

Categories

Resources