I am trying to do an assignment where it makes random lotto numbers. I have it all built out, but when I put the first value in and it runs it will post to the HTML. Then doing a second value will concatenate to the first instead of clearing. I've tried .reset and value = "" but I must be doing something wrong. I tried searching the old posts, but couldn't find anything as I wasn't sure exactly what the problem was.
var buttons = document.getElementById("create");
var numbers = [];
var shownSelection = ""
function makeIt() {
var input = document.getElementById("count").value;
var resultsDiv = document.getElementById("results");
if (input > 8) {
alert("Too many numbers. Please try less than 8.")
} else if (input < 1)
alert("Nothing to predict.")
else
for (var i = 0; i < input; i++) {
numbers[i] = Math.ceil(Math.random() * 99);
}
for (var i = 0; i < input; i++) {
if (i == input - 1) {
shownSelection = shownSelection + numbers[i];
} else {
shownSelection = shownSelection + numbers[i] + "-";
}
}
resultsDiv.innerHTML =
shownSelection;
document.getElementById("results").value = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lucky Lotto Game</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" defer></script>
</head>
<body>
<div class="entry">
<ul>
<li><input type="text" id="count" placeholder="Enter number between 1 and 8" /></li>
</ul>
</div>
<div id="buttons" class="buttons">
<button id="create" onclick="makeIt()" class="create">Get my numbers</button>
</div><br><br><br>
<span id="results"></span>
</body>
</html>
You should initialize your 'shownSelection' variable inside the function so it will be empty each time you press the button:
var buttons = document.getElementById("create");
var numbers = [];
function makeIt() {
var shownSelection = ""
var input = document.getElementById("count").value;
var resultsDiv = document.getElementById("results");
if (input > 8) {
alert("Too many numbers. Please try less than 8.")
} else if (input < 1)
alert("Nothing to predict.")
else
for (var i = 0; i < input; i++) {
numbers[i] = Math.ceil(Math.random() * 99);
}
for (var i = 0; i < input; i++) {
if (i == input - 1) {
shownSelection = shownSelection + numbers[i];
} else {
shownSelection = shownSelection + numbers[i] + "-";
}
}
resultsDiv.innerHTML =
shownSelection;
document.getElementById("results").value = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lucky Lotto Game</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" defer></script>
</head>
<body>
<div class="entry">
<ul>
<li><input type="text" id="count" placeholder="Enter number between 1 and 8" /></li>
</ul>
</div>
<div id="buttons" class="buttons">
<button id="create" onclick="makeIt()" class="create">Get my numbers</button>
</div><br><br><br>
<span id="results"></span>
</body>
</html>
Related
I am trying to create a program that takes a user's input from the html and runs it through a for loop, and then displays the translated input. The problem is that the output just displays undefined. The function that translates the user's input in the inputbox is supposed to be called with the button in the html, but clicking it changes nothing, and the output just stays "undefined"
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
console.log(resultArray.join('').toUpperCase());
document.getElementById('input').innerHTML = input;
document.getElementById('output').innerHTML = resultArray.join('').toUpperCase();
console.log(resultArray);
}
function translateInput() {
let userInput = document.getElementById('input').value
let translateResult = whaleTalk(userInput);
updateOutput(translateResult);
}
function updateOutput(input) {
document.getElementById('output').innerHTML = input;
}
whaleTalk();
updateOutput();
<!DOCTYPE html>
<head>
<title>Whale Talk Translator</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="whaletranslator.css" rel="stylesheet" type="text/css" />
<style>
</style>
</head>
<body>
<header style="color: white;">Whale Talk Translator </header>
<h2>Input anything you want into the box below and hit the button to translate it.</h1>
<div class="translatorBox">
<input value="" id="input" type="text" class="inputBox" placeholder="Text to translate">
<br>
<div class="container">
<div class="center">
<button class="translateButton" onclick="updateOutput()">Translate</button>
</div>
</div>
<div class="container">
<div class="center">
<button class="reloadButton" onClick="window.location.reload();">Reload</button>
</div>
</div>
</div>
<p style="padding: 2em">Translated input:</p>
<div class="output">
<p id="output"></p>
</body>
<script src="whaletranslator.js" type="text/javascript"></script>
</html>
Your function returns undefined because you are not returning anything from it. Try this:
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
return resultsArray.join('').toUpperCase()
}
Now when your translationResult variable will be the string that your updateOutput method will set to the innerHtml of the element with id 'output'. Instead of calling the two methods at the bottom you can now just call translateInput()
You haven't satisfied the argument for the method updateOutput, the "undefined" message is caused because the argument is not defined in your call
More Details:
Program should receive a number and continue receiving numbers [from users input] until
a zero is entered. When a zero is entered, the program should output how many positive and how
many negative numbers have been entered, and then stop.
So far I've only been able to enter one number at a time in the textfield and only been able to output one value that is either positive or negative.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Exercise Two</title>
<link href="ex2.css" rel="stylesheet">
<script type="text/javascript" src="ex2.js"></script>
</head>
<body>
Enter number (Press 0 to stop)
<input type="text" id="num">
<button onclick="check()">Submit</button>
</body>
</html>
Javascript
function check(){
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
var x = parseInt(document.getElementById("num").value);
var posCount = 0;
var negCount = 0;
if (x > 0) {
posCount++;
}else{
negCount++;
}
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
}
You could try appending the data to a hidden input element:
function check() {
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
var x = parseInt(document.getElementById("num").value);
var totals = document.querySelector("#totals");
var posCount = totals.dataset.positives;
var negCount = totals.dataset.negatives;
if (x === 0) {
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
totals.dataset.positives = 0;
totals.dataset.negatives= 0;
} else if (x > 0) {
totals.dataset.positives = ++posCount;
} else {
totals.dataset.negatives= ++negCount;
}
}
<p>Enter number (Press 0 to stop)</p>
<input type="text" id="num">
<input type="hidden" id="totals" data-positives='0' data-negatives='0'>
<button onclick="check()">Submit</button>
UPDATE
To achieve this, you can create a positive and negative variable outside of the count function and then check each input value; if the value entered zero, you can call your alert function and print the result.
Here is the working code:
var posCount = 0;
var negCount = 0;
function printOutput () {
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
}
function check(){
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
var x = parseInt(document.getElementById("num").value);
document.getElementById("num").value = ''
if (x > 0) {
posCount++;
}else if (x < 0){
negCount++;
} else {
printOutput();
// re-initiate value
posCount = 0;
negCount = 0;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Exercise Two</title>
<link href="ex2.css" rel="stylesheet">
<script type="text/javascript" src="ex2.js"></script>
</head>
<body>
Enter number (Press 0 to stop)
<input type="text" id="num">
<button id="submit-btn" onclick="check()">Submit</button>
</body>
</html>
I am trying to create the below game. The Javascript textcontent however is not displaying anything.
The Computer selects a random "secret" number between some min and max.
The Player is tasked with guessing the number. For each guess, the application informs the user whether their number is higher or lower than the "secret" number.
Extra challenges:
Limit the number of guesses the Player has.
Keep track/report which numbers have been guessed.
My code is as follows:
const submitguess = document.querySelector('.submitguess');
const inputno = document.querySelector('#secretno');
const resultmatch = document.querySelector('#resultmatch');
const highorlow = document.querySelector('#highorlow');
const guesslist = document.querySelector('#guesslist');
let randomNumber = Math.floor(Math.random() * 10) + 1;
let count = 1;
let resetButton;
function guessvalid() {
let input = Number(inputno.value);
//alert('I am at 0');
if (count === 1) {
guesslist.textContent = 'Last guesses:';
}
guesslist.textContent += input + ', ';
if (randomNumber === input) {
//alert('I am here 1');
resultmatch.textContent = 'Bazingaa!!! You got it absolutely right';
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else if (count === 5) {
resultmatch.textContent = 'Game Over !! Thanks for playing.';
//alert('I am here 2');
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else {
//alert('I am here 3');
resultmatch.textContent = 'Sorry the secret no and your guess do not match.Please try again !!';
if (randomNumber > input) {
//alert('I am here 4');
highorlow.textContent = 'Hint.The guess was lower than the secret no.';
} else if (randomNumber < input) {
//alert('I am here 5');
highorlow.textContent = 'Hint.The guess was higher than the secret no.';
}
}
count = count + 1;
input.value = '';
}
submitguess.addEventListener('click', guessvalid);
function GameOver() {
inputno.disabled = true;
submitguess.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Lets play again';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', reset);
}
function reset() {
count = 1;
const newDisplay = document.querySelectorAll('.display p');
for(let k = 0 ; k < newDisplay.length ; k++) {
newDisplay[k].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
inputno.disabled = false;
submitguess.disabled = false;
inputno.value = '';
randomNumber = Math.floor(Math.random() * 10) + 1;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Hi Low</title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h3>Lets guess the secret number between 1 and 10</h3>
<h4>You have 5 chances to guess </h4>
</header>
<br/>
<br/>
<form class='form'>
<div class='secretno'>
<label for='secretno'>Please enter your guess for secret no (between 1 and 10):</label>
<input id='secretno' type='number' name='secretno' step='1' min='1' max='10' required>
<span class='validity'></span>
<input type='button' class='submitguess' value='submit'>
</div>
</form>
<br/>
<br/>
<div class='display'>
<p id='resultmatch'> </p>
<p id='highorlow'> </p>
<p id='guesslist'> </p>
</div>
Because I don't have enough contribution I have to write as an answer.
First is here
<input type='submit' class='submitguess'>
you should prevent the form to be executed and refresh so you have to add preventdefault. or simply change input submit to button type="button"
Second
const resetParas = document.querySelectorAll('.display p');
You should check this one. resetParas set but you check display length.
I just started learning javascript. I develop an input box that user enters a number in. so program decrease number to zero.
my problem is here; I enter a number and show same it in output, but show a decreasing number.
my JS code :
function test() {
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var Exp_MyInput = document.getElementById('output01').innerHTML = "Number: " + MyInput;
for (var i = 1; i < 4; i++) {
document.getElementById('output01').innerHTML = MyInput;
}
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="StyleSheet.css" />
<script src="Script.js"></script>
<title>EyeProctect Project</title>
</head>
<body>
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick=test()>Let's Go!</button>
<p id="output01"></p>
</body>
</html>
What am I do?
If you meant counting down from number provided in input field down to zero using for loop then you can work with this approach:
function test() {
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var output = document.getElementById('output01');
output.innerHTML = '';
for (var i = MyInput; i > 0; i--) {
output.innerHTML += "Number: " + i + "<br>";
}
}
I sort of started coding for this. It's almost working.
My goals:
1) Check for the length or url's entered in a field (the total length) and reduce each link's length by 20 if the length is greater than 20
2) Determine the characters left in an input field
The javascript in profile.js (prototype):
function checkurl_total_length(text) {
var text = "";
var matches = [];
var total_length = 0;
var urlRegex = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
text.scan(urlRegex, function(match){ matches.push(match[0])});
for (var index = 0; index < matches.length; ++index) {
item = matches[index];
reduce_length = matches.length*20;
if(item.length>20) {
total_length = total_length + item.length - reduce_length;
}
else {
total_length = total_length + item.length;
}
}
return total_length;
}
function count_characters(field){
var limitNum=140;
var link_length = 0;
if(checkurl_total_length(field.value)!=0) {
link_length =link_length+ checkurl_total_length(field.value);
}
else {
link_length = 0;
}
limitNum = limitNum+link_length;
if( link_length !=0 ){
$("links").update("with links");
}
left = limitNum-field.value.length;
$("count").update(left);
}
THE HTML
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JUST A TEST FILE</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="profile.js" type="text/javascript"></script>
</head><body>
<h1>
CHARACTERS COUNT
</h1>
<div class="container_24">
<h2 id="title2">
TESTING
</h2>
<div class="grid_24">
<div id="count"></div>
<br /s>
<div id="links"></div>
<form >
<textarea wrap="hard" onpaste="count_characters(this);" onkeyup="count_characters(this);" onkeydown="count_characters(this);" id="updates" onfocus="count_characters(this);" name="test"/> </textarea>
<input type="submit" value=" " name="commit" disabled=""/>
</form>
</div>
</div>
<!-- end .container_24 -->
</body></html>
Counting characters left is working but checking for url and the length of the url isn't. Any hints on why this isn't working?
not sure, but should this be
checkurl_total_length(field.value!=0) // ) != 0