Adding JavaScript calculation function to HTML form - javascript

I am trying to link a basic calculation in an external JavaScript
The form is pretty simple and the function just checks to make sure the step number is even. I have reviewed the code many times, but when I enter the numbers and hit submit nothing happens. Any suggestions? Its seems like I just don't have the function and input elements linked correctly.
here is the code:
function evenNumbers() {
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
while (startNumber + stepNumber <= endNumber) {
if (startNumber <= endNumber){
if (startNumber % 2 === 0 && stepNumber % 2 === 0) {
startNumber += stepNumber;
alert(startNumber);
} else if (startNumber % 2 !== 0 && stepNumber % 2 === 0) {
startNumber += 1 + (stepNumber);
alert(startNumber);
} else {
alert("Please enter a positive number for the step value.");
}
} else {
alert("Please enter an ending number greater than the start number.");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="number" id="startNumber"/><br/>
<label>End: </label>
<input type="number" id="endNumber"/><br/>
<label>Step by:</label>
<input type="number" id="stepNumber"/><br/>
<button onclick="evenNumbers();">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>

Try this:
In .js file
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);

I have removed your actual code for now, because it has some issues whereby you can end up in an infinite loop (I definitely did and it crashed Chrome 😊).
Your issue was in your HTML
Before
<button onclick("evenNumbers();")>Submit</button>
After
<button onclick="evenNumbers();">Submit</button>
function evenNumbers() {
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
alert(startNumber + ',' + endNumber + ',' + stepNumber);
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="text" id="startNumber"/><br/>
<label>End: </label>
<input type="text" id="endNumber"/><br/>
<label>Step by:</label>
<input type="text" id="stepNumber"/><br/>
<button onclick="evenNumbers();">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>

function evenNumbers() {
//var evenNumberBtn = document.querySelector("button");
//evenNumberBtn.addEventListener("click", evenNumbers);
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
while (startNumber + stepNumber <= endNumber) {
if (startNumber <= endNumber){
if (startNumber % 2 === 0 && stepNumber % 2 === 0) {
startNumber += stepNumber;
alert(startNumber);
} else if (startNumber % 2 !== 0 && stepNumber % 2 === 0) {
startNumber += 1 + (stepNumber);
alert(startNumber);
} else {
alert("Please enter a positive number for the step value.");
}
} else {
alert("Please enter an ending number greater than the start number.");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="text" id="startNumber"/><br/>
<label>End: </label>
<input type="text" id="endNumber"/><br/>
<label>Step by:</label>
<input type="text" id="stepNumber"/><br/>
<button onclick="evenNumbers()">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>

The first two lines inside evenNumber function need to be outside the function, Otherwise your code never reaches inside that block.
$( document ).ready(function() {
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
function evenNumbers() {
/*
your code here
*/
}
});
Also the logic inside the evenNumbers seems wrong. You might need to change that too.

Related

Input not being read by code in JavaScript

I'm having trouble with my JS form. So I'm creating a change calculator which takes in two input values - the price and cash. When I explicity put in the actual values inside JS code (like the ones I commented out after confirmValues()), it works just fine. But when I put it in the actual input box, it doesn't give work anymore. Is there something weird with my HTML or JS? Thanks!
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title> Change calculator</title>
</head>
<body>
<form>
How much does the item cost? <input type="number" id="price" name ="price"/>
<br/> <br/>
How much cash do you have? <input type="number" id="cash" name="cash"/><br/> <br/>
<input type="button" value="Enter" onclick="confirmItems();"/>
</form>
<p id="confirmation"></p>
<p id ="change"></p>
</body>
var itemCost = document.getElementById("price");
var cash = document.getElementById("cash");
var confirmation = document.getElementById("confirmation");
function confirmItems() {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.value + " and you have $" + cash.value + " to pay for it.";
createConfirmationBtn();
}
function createConfirmationBtn() {
let confirmationBtn = document.createElement("BUTTON");
const confirmationBtnText = document.createTextNode("Confirm");
confirmationBtn.appendChild(confirmationBtnText);
confirmation.appendChild(confirmationBtn);
confirmationBtn.onclick = function() {
confirmValues();
}
}
let changeEl = document.getElementById("change");
function confirmValues() {
if (parseFloat(cash.value) < parseFloat(itemCost.value)) {
changeEl.innerHTML = "Not enough cash";
} else if (parseFloat(cash.value) == parseFloat(itemCost.value)) {
changeEl.innerHTML = "Your change is $0.";
} else {
calculateChange();
}
}
// cash.value = 500;
// itemCost.value = 33.44;
let remainder = parseFloat(cash.value) - parseFloat(itemCost.value);
let finalOutput = new Array();
function calculateChange() {
while (remainder > 0) {
if (remainder >= 100) {
findChange(100.00);
} else if (remainder >= 50.00) {
findChange(50.00);
} else if (remainder >= 20.00) {
findChange(20.00);
} else if (remainder >= 10.00) {
findChange(10.00);
} else if(remainder >= 5.00) {
findChange(5.00);
} else if (remainder >= 1.00) {
findChange(1.00);
} else if (remainder >= 0.25) {
findChange(0.25);
} else if (remainder >= 0.10) {
findChange(0.10);
} else if (remainder >= 0.05) {
findChange(0.05);
} else {
findChange(0.01);
}
}
changeEl.innerHTML = finalOutput;
}
function findChange(value) {
//Step 1. Get number of dollar for each type of dollar
let dValue = parseInt(remainder / value);
// Step 2. Storing numDValue in an array
finalOutput.push("[$" + value + " x" + dValue+"]");
remainder = parseFloat(remainder - (value * dValue));
remainder = parseFloat(remainder.toFixed(2));
}
You need to have the vars inside the functions that need them or they will not pick up what the user enters
You can show and hide the confirm button
DRY, Don't Repeat Yourself
function confirmValues() {
let itemCost = document.getElementById("price").value;
let cash = document.getElementById("cash").value;
const confirmation = document.getElementById("confirmation");
const changeEl = document.getElementById("change");
const confirm = document.getElementById("confirm");
cash = isNaN(cash) || cash === "" ? 0 : +cash; // test valid input
itemCost = isNaN(itemCost) || itemCost === "" ? 0 : +itemCost;
if (cash < itemCost) {
changeEl.innerHTML = "Not enough cash";
} else {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.toFixed(2) + " and you have $" + cash.toFixed(2) + " to pay for it.";
changeEl.innerHTML = "Your change is $" + (cash - itemCost).toFixed(2);
confirm.classList.remove("hide");
}
}
.hide {
display: none;
}
<title> Change calculator</title>
<form>
How much does the item cost? <input type="number" id="price" name="price" />
<br/> <br/> How much cash do you have? <input type="number" id="cash" name="cash" /><br/> <br/>
<input type="button" value="Enter" onclick="confirmValues();" />
<input type="button" id="confirm" class="hide" value="Confirm" onclick="alert('Confirmed!')" />
</form>
<p id="confirmation"></p>
<p id="change"></p>

How to fix the show/hide button on input change based on if/else condition

I am learning jquery. I have an HTML & jquery code. I want to show the button only if my answer is true on input value otherwise it should stay hidden. Also, I want to show the questions on my screen. See, if anyone can help. thanks
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var ans = 5;
$(document).ready(function() {
$("#bot").keyup(function() {
if (ans == floor) {
$("#pete").css("display", "block");
} else {
$("#pete").css("display", "none");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;">
use show() and hide() functions and i dont know when your floor and ans will be equal.
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ans = 5;
floor=6; //for testing i gave
$("#bot").keyup(function() {
if (ans == $('#bot').val())
$("#pete").show();
else
$("#pete").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>What number comes after 4?</label>
<input type="number" id="bot" required="required"/>
<input type="submit" id="pete" style="display:none;" >
Here is the complete code for your requirement .
Use innerHTML to priint the question in the screen and .value to obtain the value entered by user ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p id="question"></p>
<p>Name: <input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" style="display:none;" >
</body>
</html>
<script type="text/javascript">
var random = Math.random();
var range = random * 2 ;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
document.getElementById('question').innerHTML = ques1;
var ans = 5;
$("#bot").keyup(function() {
var ansFromInput = document.getElementById('bot').value;
console.log("ans , floor" , ans , ansFromInput);
if (ans == ansFromInput) {
$("#pete").css("display", "block");
}
else {
$("#pete").css("display", "none");
}
});
</script>
You can do something like that ,
Here using class to hide the button, we can add and remove class to achieve that.
var random = Math.random();
var range = random * 2;
var incrment = range + 1;
var floor = Math.floor(incrment);
var ques1 = "what comes after 4?";
var floor = 5;
$('#ques').text(ques1);
$(document).ready(function() {
$('#bot').on('input',function(e){
if ($('#bot').val() == floor) {
$("#pete").removeClass('hide');
} else {
$("#pete").addClass('hide');
}
});
});
.hide{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> <p id="ques"> </p> </label>
<p><input type="text" id="bot" required="required"></p>
<input type="submit" id="pete" class="hide">

Difference between a given number and 13 displays -13 for every number I enter

Code:
<!DOCTYPE html>
<html>
<head>
<title>xxxxxxxxxxx</title>
</head>
<input id="nr1" type="text"></br>
<input id="calc" type="button" onClick="calc();return false;" value="calc">
<div id="result"></div>
<script>
const nr1 = document.getElementById("nr1").value;
const nr2 = 13;
const button = document.getElementById("calc");
function calc() {
if(nr1 - nr2 >= 13){
document.getElementById("result").innerHTML = (nr1-nr2)*2;
}
else {
document.getElementById("result").innerHTML = nr1-nr2;
}
}
</script>
</body>
</html>
Why does it display -13 for every number I enter?
I think I'm missing something, but I just can't get what's happening.
The value of user input is stored at DOM load which is empty at that point. In other words, cache the input, not its value. The input must be converted to a number to perform arithmetic.
const
nr2 = 13,
nr1 = document.getElementById("nr1"),
button = document.getElementById("calc");
function calc() {
let n1 = Number( nr1.value ); // convert to number. See browser support
if(n1 - nr2 >= 13) {
document.getElementById("result").innerHTML = (n1-nr2)*2;
} else {
document.getElementById("result").innerHTML = n1-nr2;
}
}
<input id="nr1" type="text"></br>
<input id="calc" type="button" onClick="calc();return false;" value="calc">
<div id="result"></div>

User guesses a number from 1-1000 using functions

I am trying to make a program that prompts the user to guess a number from 1 to 1000. The program generates a random number and then the user has to guess the number until they get it right. The program alerts the user if their guess is too low or too high. Upon entering the right number, they are congratulated and asked if they want to run it again. I have read my book and even looked online for guidance, but against my best effort all it does is display the text field with the calculate button...no window messages or anything. Please help as I am stumped. This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>
There is a } missing in line 45
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9.25</title>
<script type="text/javascript">
var inputField;
var guess;
var calculateButton;
function startGame() {
window.alert("Guess a number between 1 and 1000 in the text field.");
calculateButton = document.getElementById("calculate");
//calculateButton.disable = true;
guessNum();
}
function randomNum(random) {
return Math.floor(1 + (Math.random() * 999));
}
function guessNum() {
inputField = document.getElementById("entry");
guess = parseFloat(inputField.value);
while (randomNum(random) != guess) {
if (randomNum(random) > guess) {
window.alert("Too low. Try again.");
}
else if (randomNum(random) < guess) {
window.alert("Too high. Try again.");
}
}
window.alert("Congratulations. You guessed the number!");
playAgain();
}
function playAgain() {
var again = window.prompt("Enter 'yes' to play again");
if (again == "yes") {
Start();
calculateButton.disabled = false;
}
else if (again == "no") {
alert ("Thank you for playing! Goodbye!")
calculateButton.disabled = true;
}
}
function Start() {
var calculateButton = document.getElementById("calculate");
calculateButton.addEventListener( "click", startGame, false );
}
window.addEventListener("load", Start, false);
</script>
</head>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
</div>
</form>
</body>
</html>
Jquery way if you mind
var a = Math.floor((Math.random() * 100) + 1);
$(document).ready(function(){
$('#numberrandom').text(a);
});
$('#calculate').bind('click',function(){
entrynumber=$('#entry').val();
if(entrynumber > a){
alert('Your number is higher than it')
}
else if(entrynumber < a){
alert('Your number is lower than it')
}
else if(entrynumber == a){
alert('nice you won')
location.reload();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form action="#">
<div>
<label>Your guess here:
<input id="entry" type="number">
</label>
<br>
<input id="calculate" type="button" value="Calculate">
<span>generated number: </span><span id='numberrandom'></span>
</div>
</form>
</body>

Why is `pieceOfText` undefined?

I am creating a little guessing game involving decrypting text, but there is a variable inside my JavaScript code that is not working correctly. This variable, called pieceOfText, is supposed to be equal to a random piece of text generated from an array of 3 pieces of encoded text. However, when I retrieve the value of said variable, it outputs undefined.
Here is the code I have now:
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
<!DOCTYPE html>
<html>
<HEAD>
<META CHARSET="UTF-8" />
<TITLE>Decryption Guessing Game</TITLE>
</HEAD>
<BODY>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<SCRIPT LANGUAGE="Javascript">
</SCRIPT>
</BODY>
</html>
The line commented out is possibly preventing my guessing game from running properly because pieceOfText is set to undefined. I was currently doing some debugging at the time when I found this out. One question I found with a similar dilemma was more oriented towards ECMAScript 6 (I'm not sure if I'm using that), and others I found weren't even related to JavaScript. So, what caused this and how can I fix it?
You wrote Math.random instead of Math.random() (you forgot to actually call the function):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Decryption Guessing Game</title>
</head>
<body>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<script>
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
</script>
</body>
</html>

Categories

Resources