Javascript Addition operator Confusing & Not Working - javascript

ok im trying to learn JS but its small thing like this that is making it hard and making me want to say just forget it
for example w3schools says A+=B is the same as saying A = A + B
but when i change this code around to NOT use the A+=B operand it and code it to work as A = A + B doesnt work the same!
so that means A+=B does NOT mean the same as A = A + B then!
heres w3chools example im learning "while" loops at moment and heres is my problem below and this is THEIR code it writes "The Number is 1-19" on a new line each time as it should
<h1>JavaScript while</h1>
<p id="demo"></p>
<script>
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
here is MY Code Below and im basicall rewriting it from "A+=B to A = A + B" and it only writes "The Number is" ONE TIME and the number 1-19 on same line!
<h1>JavaScript while</h1>
<p id="demo"></p>
<script>
var text = "<br>The number is ";
var i = 0;
while (i < 10) {
text = text + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

You can concat the string each time in the loop:
var text = "";
var i = 0;
while (i < 10) {
var curtext = document
.getElementById("demo")
.innerHTML;
document
.getElementById("demo")
.innerHTML = curtext + "<br>The number is " + i;
i++;
}
<div id="demo"></div>

The difference between you code and W3S's is that you add the i value to text each time not the desired text so the output would be <br>The number is 123456789 to avoid that you should add <br>The number is every time:
var text = '',
text2 = ''
prefix = '<br>The number is',
i = 0;
console.clear();
while (i < 10) {
var toAppend = prefix + i
text += toAppend;
text2 = text2 + toAppend;
i++;
}
document.write(text);
document.write('<br />*****************************');
document.write(text2);

Related

Having a problem with my javascript code - computer has to guess the digit value I input

First I created a version of this which worked where I didn't input the value on the webpage:
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == 3)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
</script>
Then this is the version I'm trying to create where I enter in the input on the webpage, and then the computer tries to guess it, but it's not executing at all or showing anything when I try to debug in the console.
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
document.getElementById("fingersSubmit").onclick = function ()
{
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == numberOfFingers)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
}
I'm a beginner coder so if there is any useful knowledge pertaining to this in addition to showing me the correct code, then I'd greatly appreciate that!
Thanks!
Here's a working version where I tried to stay as close to your original code as possible:
<html>
<body>
<p>Enter in how many fingers (between 0 and 5) you are holding up:</p>
<p>
<input id="fingersInput" type="text" />
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
document.getElementById('fingersSubmit').onclick = function() {
i = 0;
var fingersText = '';
var correctGuesses = 0;
var numberOfFingers = document.getElementById('fingersInput').value;
while (i < 5) {
var computerGuess = Math.floor(Math.random() * 5 + 1);
fingersText += '<p>' + computerGuess + '</p>';
if (computerGuess == numberOfFingers) {
correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById('fingers-game-v2').innerHTML = fingersText;
document.getElementById('computer-guess-results').innerHTML =
'<h3>' +
'Number of times the computer guessed correctly: ' +
'</h3>' +
correctGuesses;
};
</script>
</body>
</html>
The main reason your code wasnt working is because you need to get the input value when the button is clicked (i.e. place it inside the onclick)
The other issue is that you redeclare correctGuesses inside the if block, so you should just remove the var keyword, otherwise you will get NaN
Finally, this isn't strictly a problem with your code, but moving forward you should be aware that numberOfFingers is a string whereas correctGuesses is a number. In your if block, you compare the two values and it works because you used ==, which only checks value. It's typically better practice to use === which is a stricter equality check, comparing both value and type. So moving forward, you might want to make sure to convert numberOfFingers to a number before you do the equality check

adding style to items in an array

I am doing a madlibs-type program. Prompts ask for words, which are then added to a string. I would like the words used from the prompts to be underlined when they are displayed with the rest of the string. I have created an array with all the prompts. Now, I just need to know how to run through that array and change the text-decoration to "underline". I know I need to use a for-loop through the array, but not sure of how to approach it.
What is the best way to make this happen?
HTML:
<body>
<div id = "story-space">
</div>
<script src = "madlibs.js"></script>
</body>
JS:
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3, prompt4];
var text = "There was once was a " + prompt1 + " from " + prompt2 + " who liked to " + prompt3 + "."
document.getElementById("story-space").innerHTML = text;
Why can you add the html style like this
var text = "There was once was a <span style='text-decoration:underline'>" + prompt1 + "</span> from <span style='text-decoration:underline'>" + prompt2 + "</span> who liked to <span style='text-decoration:underline'>" + prompt3 + "</span>."
one simple way you can do it it as follows, note that you need to check for empty strings returned from prompt though, which is not handled in this answer,
var questions = ['an animal', 'a city', 'an activity'],
answers = [];
// create source string with placeholders that
// can be replaced with values in from prompts
var sourceText = "There was once was a {0} from {1} who liked to {2}."
//loop thru questions array and store answers in 'answers' variable
for (var q = 0; q < questions.length; q++) {
//create answer as span element
var question = questions[q],
answer = '<span style="text-decoration:underline;">';
answer += prompt('Enter ' + question);
answer +='</span>';
//update source text's 'qth' placeholder with answer
sourceText = sourceText.replace( new RegExp( "\\{" + q + "\\}", "g" ), function() {
return answer;
});
}
//update the target element's innerHTML
document.getElementById("story-space").innerHTML = sourceText;
You can try something like this by mapping all the prompts with an underline class.
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3];
prompts = prompts.map(prompt => `<span class="underline">${prompt}</span>`)
var text = "There was once was a " + prompts[0] + " from " + prompts[1] + " who liked to " + prompts[1] + "."
document.getElementById("story-space").innerHTML = text;
.underline {
text-decoration: underline;
}
<div id = "story-space">
</div>
You can also try something like below where you just provide the pre-text for your prompt and let the Map and Reduce do the rest of the job for you.
let textPromptMap = new Map();
textPromptMap.set("There was once was a ", prompt("Enter a animal."))
textPromptMap.set(" from ", prompt("Enter a city."))
textPromptMap.set(" who liked to ", prompt("Enter an activity."))
const text = [...textPromptMap.keys()]
.reduce((a, b) =>
`${a}${b}<span class="underline">${textPromptMap.get(b)}</span>`, ""
)
document.getElementById("story-space").innerHTML = text;
.underline {
text-decoration: underline;
}
<div id = "story-space">
</div>

use math.max on variables and display corresponding variables

I have a question with my JavaScript code (I am quite new at this...). I am making a test where I will calculate the score of the participants by using their answers. I have multiple variables where I store these answers. And also the calculation of the score is going ok. Then I have a table with the scores. That is like this:
<script type="text/javascript">
var row1col1var="Fruit";
var rowicol2var="% of how much I love them";
var applep=34; //result from score calcultaion
var row2col1var="Apple";
var bananasp=65; //result from score calcultaion
var row3col1var="Bananas";
document.write('<center><table width="50%" border="0">');
document.write('<tr align="center"><td>' + row1col1var + '<\/td><td>' + rowicol2var + '<\/td><\/tr>');
document.write('<tr align="center"><td>' + row2col1var + '<\/td><td' + applep + "%" + '<\/td><\/tr>');
document.write('<tr align="center"><td>' + row3col1var + '<\/td><td' + bananasp + "%" +'<\/td><\/tr>');
document.write('<\/table><\/center>'); </script>
Here I display the results per "fruit" in a table. What I cannot get to work is this:
I want to pick out the best score (in this case 65, for Bananas) and display: "You love Bananas the most." (ie link 65 to Bananas and display Bananas). I was trying to give the cells an id with the name Apples or Bananas and calling on the id to display it, but this did not work.
My problem breaks down in two pieces:
1. I cannot get math.max to work on variables.
2. I do not know how to link the highest score to its "name" (ie 65 belongs to Bananas).
I hope you can help me!!
You need to use more appropriate way for coding. For storing data, you can use object or array. I am using an array for this example.
Check this :
<html>
<head>
<script type="text/javascript">
function getScore(){
var scoreArr = [];
scoreArr.push(['apple', '35']);
scoreArr.push(['apple', '65']);
var maxPercentage = null;
var lovedFruit = '';
var finalScore = '<center><table width="50%" border="0"><tr align="center"><th>Fruits</th><th>% of how much I love them</th></tr>';
for (var i = 0; i < scoreArr.length; i++) {
finalScore += '<tr align="center"><td>' + scoreArr[i][0] + '</td><td>' + scoreArr[i][1] + "%" + '</td></tr>';
if (maxPercentage === null) {
lovedFruit = scoreArr[i][0];
maxPercentage = parseInt(scoreArr[i][1]);
} else {
if (maxPercentage < parseInt(scoreArr[i][1])) {
lovedFruit = scoreArr[i][0];
maxPercentage = parseInt(scoreArr[i][1]);
}
}
}
finalScore += '</table><br>Result is : ' + maxPercentage + ' belongs to ' + lovedFruit + '</center>';
// WITH JAVASCRIPT
var container = document.createElement('div');
container.innerHTML = finalScore;
document.body.insertBefore(container, null); //append div to end
// WITH JQUERY
// $('body').append(finalScore);
}
</script>
</head>
<body onLoad=getScore()>
</body>
</html>
It will store your data in array and then you can do whatever you want in more sophisticated way.

Running Display in textarea - JavaScript

I was wondering how to keep outputs saved in the textarea box..
I'm writing a javascript program to translate english words to pig latin, so hello would be ellhay.
Anyways, say I type in "are" and in the textarea it translates it to "reaay" and then I type in "hello" (translation "ellohay") the textarea should output "ellohay" and "reaay" under it
I've tried this (edit now trying with array called outputs):
function printLatinWord() {
<!--
var outputs = new Array();
var input = document.form.english.value;
var lowercase = input.toLowerCase();
var fininput = lowercase.split (" ");
var output = "";
for (i = 0; i < fininput.length; i++) {
var result = fininput[i];
output += result.substring (1, result.length) + result.substring(0,1) + "ay ";
document.form.piglat.value = output + "\n";
var j = 0;
output = outputs[j];
j++;
}
/*
var newtext = "\n";
document.form.piglat.value = newtext + document.form.piglat.value;
//trying to keep running display of conversions
var newtext = ("\n");
output += newtext;*/
}
Basically nothing new happens with
At the end the var newtext is supposed to be where the outputs are stored.. but I'm not sure exactly how to get the values from the textarea and keep them there to be displayed under new outputs, if that makes sense.
document.form.piglat.value += newtext; appends newtext to the existing value. If you want it prepended instead, use
document.form.piglat.value = newtext + document.form.piglat.value;

How to add a prefix/suffix to text per line using javascript?

how would i add a prefix per line to a text area.. example:
this is the content of the textarea:
hello124
and i would want to add a [b] prefix and suffix to each line so that when i click a button the result will be:
[b]hello[/b]
[b]124[/b]
please help me :(
text = document.getElementById("the_textarea").value;
document.getElementById("the_textarea").value = text.replace(/.+/g, "[b]$&[/b]");
Example:
using joins and splits:
var prefix = '[b]', suffix = '[/b]',
txt = document.getElementById('myText');
txt.value = prefix + txt.value.split('\n').join(suffix + '\n' + prefix) + suffix;
Using only plain Javascript, you can do:
var textArea = document.getElementById("yourTextAreaID");
var lines = textArea.value.split("\n");
for (var i = 0; i < lines.length; ++i) {
lines[i] = "[b]" + lines[i] + "[/b]";
}
textArea.value = lines.join("\n");
Or, as #Alin Purcaru suggested, without using a loop:
var textArea = document.getElementById("yourTextAreaID");
textArea.value = "[b]" + textArea.value.split("\n").join("[/b]\n[b]") + "[/b]";
<script language="javascript" type="text/javascript">
function TextDefine(val){
var i= 0;
var array1 = val.value.split("\n");
for ( i = 0; i < array1.length; i++) {
array1[i] = "[b]" + array1[i] + "[/b]";
}
val.value = array1.join("\n");
}
</script>
<textarea name="data" id="data"></textarea>
<input type="button" name="submit1" value="Submit" onclick="TextDefine(document.getElementById('data'))" />
Convert the string into an array starting at position 1 of the array.
Push the prefix at position 0 of the array.
Convert the array back to a string with join.

Categories

Resources