.toLowerCase() not working among other things not working - javascript

JS
var score = 0
var yes = "yes"
var pokemonName = [];
var bg = [];
var index = 0;
document.getElementById('repete').style.visibility = 'hidden';
(function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
})();
function loop() {
var myAnswer = document.getElementById("myAnswer");
var answer = myAnswer.value;
if (answer.toLowerCase().trim() == pokemonName[num].toLowerCase().trim()) {
document.getElementById("text").innerHTML = "Correct, do you want to try again?";
score++
document.getElementById('repete').style.visibility = 'visible';
} else {
document.getElementById("text").innerHTML = "Incorrect, do you want to try again?" + "\n" + " The pokemon was " + pokemonName[num];
document.getElementById('repete').style.visibility = 'visible';
}
}
function loopRepete() {
var repete1 = document.getElementById("repete");
var replay = repete1.value;
if (replay.toLowerCase().trim() == yes.toLowerCase().trim()) {
asyncLoop();
} else {
document.getElementById("text").innerHTML = "Goodbye, your score is " + score;
location.href = 'index.html'
}
}
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pokemon Quiz</title>
</head>
<body>
<lable> Answer </lable>
<input id="myAnswer" type="text">
<button onclick="loop()">click</button>
<p id="text"></p>
<div id="repete">
<lable> Answer </lable>
<input id="loop" type="text">
<button onclick="loopRepete()">click</button>
<p id="loopText"></p>
</div>
<script src="Gen3.js">
</script>
</body>
</html>
When I try take the input from the second second button (div id = repete) and put a toLowerCase() on it it does not work, and we I remove the toLowerCase() it still doesn't work but doesn't show a console error on the page. So I am confused On what I need to try do. I have tried to google it, but I could not find anything that helped.

You have to check if num exists in pokemonName array.
Otherwise, you'll be doing something like this:
[1,2,3][5].toLowerCase() which results in undefined.toLowerCase(), and you can't call .toLowerCase() on undefined as it only exists for String.

If you want asyncLoop to be defined you can't wrap it in a IIFE like that. I suspect you did that so it would run when the page loads, however there's another way to do that and still have the function defined for later use:
// define it like a normal function
function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
}
// and call it right away
asyncLoop();

Related

How to create a button to add URL links in the form

Does anyone know how to add like a link button into a form? For example, a user clicks a + button and they can add an URL. They can add another URL if they wish and remove any links if required. Would be good to have validation for links as well.
I know for validation of the URL I can use "Check if a JavaScript string is a URL", but will need something that will validate all links if multiple have been added.
The best way to explain what I am trying to do is by looking at "Can I insert a hyperlink in my form?" in the form builder.
I just want to add links, and I don't need to display text or anything like that.
Is this what are you looking for?
Your question is a bit unclear.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
let i = 0;
let ii = 0;
function isURL(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
function removeLink(id, iid) {
console.log(id);
console.log(iid);
$(id).remove();
$(iid).remove();
return false;
}
function addLink(id) {
var input = prompt("Enter the link", "https://www.example.com");
var valid = isURL(input);
console.log(valid);
if(valid) {
var element = '<br><a id="_' + i + '" href="' + input + '">Link</a>';
console.log(element);
$(id).append(element);
let d = "'#_" + i + "'";
let dd = "'#__" + ii + "'";
let elment = ' <button type="button" id="__' + ii + '" onclick="removeLink(' + d + ', ' + dd + ')">Remove it!</button>';
$(id).append(elment);
console.log(elment);
i = i + 1;
ii = ii + 1;
}
else {
alert("The URL that you have entred is wrong.");
}
return false;
}
</script>
</head>
<body>
<form id="_form" method="POST">
<button type="button" onclick="addLink('#_form')">Add link</button>
</form>
</body>
</html>
Try it here: https://codepen.io/marchmello/pen/ZEGjMyR?editors=1000
What about DOM - not using longer form, so using URL as link text too.
function addUrl(e) {
var f = e.form;
var a = document.createElement("A");
a.href = e.value; // link URL
a.textContent = e.value; // link text
f.appendChild(a);
var x = document.createElement("INPUT");
x.type = "button";
x.value = "X";
x.onclick = remove;
f.appendChild(x);
f.appendChild(document.createElement("BR"));
}
function remove() {
var el = this, // button
parent = el.parentNode, // a must for remove
a = el.previousElementSibling; // anchor
if(el.nextSibling.tagName == 'BR') parent.removeChild(el.nextSibling);
parent.removeChild(el);
parent.removeChild(a);
}
<form>
<input name="url" size="50">
<input type="button" value="Add" onclick="addUrl(this.form.url)"><br>
</form>

How do you vertically list a string output and number them accordingly?

How do you multiply a string i.e "Enter Name" based on what number was entered in a input field and create a vertical numbered list based on said output. Any advice would be great!
Example:
hello name
hello name!
hello name
hello name!
hello name
etc.
Ive tried a couple of things. A loop seems like the logical answer, but I'm not sure how to implement it. I'm still in the process of learning javascript so not everything is immediately apparent or obvious.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width, initial-scale-1.0">
<meta http-equiv="X-UA-Compatible" content="ie-edge">
</head>
<body>
<div>
<label for="first-name">Frist Name!</label>
<input type="text" name="first-name-text" id="first-name-text" placeholder="Enter a name">
<br>
<br>
<label for="n-times">Number of times</label>
<input type="text" name="n-times-text" id="n-times-text" placeholder="Enter a number">
</div>
<div>
<p id="hello-message">Hello World!</p>
</div>
<br>
<div>
<button id="hello-button">Display Hello!</button>
<button id="reset-button">Reset</button>
</div>
<script src="script.js"></script>
</body>
</html>
javascript
let firstNameText = document.getElementById("first-name-text");
let helloMessage = document.getElementById("hello-message");
let nTimesText = document.getElementById("n-times-text")
function hideMessage( ) {
helloMessage.style.display = "none";
}
function showMessage() {
helloMessage.style.display = "";
}
function displaymessages(name) {
// let helloMessage = document.getElementById("hello-message")
helloMessage.innerText = "Hello " + name + "!";
// let goodbyeMessage = document.getElementById("goodbye-message")
// goodbyeMessage.innerText = "Goodbye " + name + "!";
showMessage();
}
hideMessage();
let helloButton = document.getElementById("hello-button");
helloButton.addEventListener('click', function() {
let firstNameText = document.getElementById("first-name-text");
displaymessages(firstNameText.value);
console.log('first name:' + firstNameText.value);
});
let resetButton = document.getElementById("reset-button");
resetButton.addEventListener('click', function() {
firstNameText.value = "";
nTimesText.value = "";
hideMessage();
});
You can use String.prototype.repeat().
let helloButton = document.getElementById("hello-button");
helloButton.addEventListener('click', function() {
let firstNameText = document.getElementById("first-name-text");
displaymessages(firstNameText.value.repeat(+nTimesText.value));
console.log('first name:' + firstNameText.value);
});
If you need to print line by line (vertically) then you have to use symbol "\n" and which will create new line.
I have changed your example code and see below,
function displaymessages(name, index) {
helloMessage.innerText += index + " " + "Hello " + name + "!\n";
showMessage();
}
let helloButton = document.getElementById("hello-button");
helloButton.addEventListener('click', function () {
let firstNameText = document.getElementById("first-name-text");
helloMessage.innerText = "";
var numberTimes = parseInt(nTimesText.value)
for (var i = 0; i < numberTimes ; i++) {
displaymessages(firstNameText.value, (i + 1));
}
});

Function returning value 'NaN'

I am writing a code that checks the user input and gives the result according to it. But the twist here is that the string can also contain the word 'dozen', which just means twelve. The thing will be cleared after looking at the following code:
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>iRock</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<form>
<label for="numDonut">Enter how many donuts you want: </label>
<input type="text" id="numDonut">
<div id="totalDonuts"></div>
<div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
JS:
//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;
function getTotalDonuts(donutString){
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if(donutString.indexOf('dozen') != -1)
finalDonuts = initialDonutCount * 12;
else
finalDonuts = initialDonutCount;
return finalDonuts;
}
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
Now here is the problem : No matter what input I give, even if it doesn't contain the word 'dozen', the function returns NaN, which is not making sense.
What can be the problem?
You need to change the function callDonut like :
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}
The problem: you don't reassign the new value of your input into the variable numDonutString
The problem you are having is you have tried to pre define your var numDonutString = document.getElementById('numDonut').value; however what this does is takes a copy of the value and it will never update that value.
So what you need to do is get the new value each time you click the SUBMIT button.
jsFiddle : https://jsfiddle.net/CanvasCode/xue6sbz2/
function getTotalDonuts(donutString){
alert(donutString);
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if(donutString.indexOf('dozen') != -1)
finalDonuts = initialDonutCount * 12;
else
finalDonuts = initialDonutCount;
return finalDonuts;
}
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}
The problem is in the callDonut function and the text box value you are getting is only at the document load, so the value is always NaN.
window.getTotalDonuts = function(donutString) {
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if (donutString.indexOf('dozen') != -1) {
finalDonuts = initialDonutCount * 12;
} else {
finalDonuts = initialDonutCount;
}
return finalDonuts || 0;
}
window.callDonut = function() {
//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;
document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
<form>
<label for="numDonut">Enter how many donuts you want:</label>
<input type="text" id="numDonut">
<div id="totalDonuts"></div>
<div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
</body>
[DEMO][1]

Reset Function for dice rolling game

I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }

how to do a printer-like text field using javascript OOP

I'm doing a printer-like text field which could show the letter one by one. I could realize it just use a function and load it as simple like:
html---
<div id="myTypingText"></div>
js---
<script>
var myString = "Place your string data here, and as much as you like.";
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += myArray.shift();
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
But I want to do more advanced, I want to let the user to change the speed and change the text, so I wrote the following one but it went wrong, why? help me .thx.
html----
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
js----
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
this.loop = function (){
if(this.len > 0 ){
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
You need to use an anonymous function in the interval if you want the loop function to be executed in the context of the Printer object. Also you need to check the length of the array each time as the len property won't be updated when the array is shifted.
function Printer() {
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.loop = function () {
if (this.myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin() {
var test = new Printer();
setInterval(function () {
test.loop()
}, test.tempo);
}
See the working fiddle
Here's another approach. Your fundamental problem was with using the this keyword. You have to remember that when you enter another function scope, the this keyword changes. You'll notice here that I cache or save 'this' to equal that, then use that new 'that' value in the function. Plunker
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
var that = this;
this.loop = function (){
if(that.myArray.length !== 0 ){
document.getElementById("myTypingText").innerHTML += that.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
</body>
</html>

Categories