I am trying to create a program that takes a user input number and compares it to a randomly generated number until the user guesses the correct number. I was having a problem where my user input number is showing up undefined while I am debugging my program but I used parseInt and fixed the issue. Now it seems it is an issue with my if else statement because I get the right use input number back now when I run a debug on my code but it now when I run it, even when I enter 1000 as my guess, it always gives me "Your guess is too low! Try a higher number."
var guessNum;//user input guess
function randomNumber(guessNum1)
{
guessNum = document.getElementById( "numInput" ).value;//getting value of user input
var guessNum1 = parseInt(guessNum);//change user input to integer
var num = Math.floor( 1 + Math.random() * 1000 ); //random number generator
if (num == guessNum1)
{
messages.innerHTML = "Congratulations! You guessed the number!";
}
else if (num < guessNum1)
{
messages.innerHTML = "Your guess is too high! Try a lower number.";
}
else (num > guessNum1)
{
messages.innerHTML = "Your guess is too low! Try a higher number.";
}
guessNum = document.getElementById( "numInput" ).value = "";//clears the textbox on screen
}
function start()
{
var guessButton = document.getElementById( "guess" );//variable for clicking button
guessButton.addEventListener( "click", randomNumber, false);
//event listener for button that starts randomNumber function
messages = document.getElementById( "messages" );
}
window.addEventListener( "load", start, false);//starts start function on screen load
<h1>Guess the Number!</h1>
<h3>Enter in a number between 1-1000 in the textbox and hit submit </h3>
<form action = "#">
<input id= "numInput" type="text" >
<input id= "guess" type="button" value="Guess" >
</form>
<p id= "messages">Enter a number to start the game </p>
Related
I have a button on that perfroms the collatz conjecture with the push of a button, and takes in the user's input. It then prints out the steps as a list into a p tag. I wanted to know how I would override the previously created steps, as I have noticed calling the method again adds to the end of the previous list.
The main reason I'm using a list is for readability, so I don't want to get rid of it unless there's a better way of doing this.
//collatz function
function collatz (){
var step = 0;
var inputCollatz = prompt("What number do you want to add?")
if (inputCollatz <= 1){
document.getElementById("collatz").innerHTML = "No steps required, already less than or equal to 1.";
}
else if(isNaN(inputCollatz)){
document.getElementById("collatz").innerHTML = "Please add a number.";
}
else if (inputCollatz.toString().indexOf('.') != -1){
document.getElementById("collatz").innerHTML = "Whole numbers please!";
}
else{
while(inputCollatz > 1){
//needed help w/ ternary operators, still need practice with it
inputCollatz = inputCollatz % 2 ? 3 * inputCollatz + 1 : inputCollatz / 2;
step++;
var item = document.createElement("li");
var text = document.createTextNode(inputCollatz);
item.appendChild(text);
var list = document.getElementById("collatz");
list.appendChild(item);
}
document.getElementById("steps").innerHTML = "Number of steps: " + step.toString();
}
}
This is the button in html.
<button onclick="collatz()">Find the number of steps.</button><br/>
<br/>
<div id="collatz"></div>
<br/>
<div id="steps"></div>
I was suggested to clear out the collatz div before each loop, which worked.
...
else {
document.getElementById("collatz").innerHTML = '';
while(inputCollatz > 1) {
....
I am submitting a frm that is basically an invoice of purchase. before submitting the form i want to implement the check that the user doesn't enter amount more than the total bill in the text box.for example if total bill is 300 and in the "paid amount" text box user enters 3000 accidentally then it should show the error message here is my code:
$("#mainform").submit(function() {
var total = $("#gtotal").val();
var paid = $("#paid").val();
alert(paid);
alert(total);
if(paid > total)
{
alert("Amount can't be greater than total");
return false;
}
return true;
});
when I alert paid and total amount they show correct values, but the if condition is not working some times it submits the form if the condition is not fulfilled sometimes i doesn't even condition is fulfilled
Try this, it may work:
var total = parseInt($("#gtotal").val());
var paid = parseInt($("#paid").val());
.val() returns strings
Convert paid and total to float with parseFloat, check them with isNaN, then compare. Like so:
paid = parseFloat(paid);
total = parseFloat(total);
if (!isNaN(paid) && !isNaN(total)) {
if (paid > total) {
...
If you aren't using decimals you may use parseInt
Add a parameter on submit function and call preventDefault method to avoid form to be submitted.
.submit(function(event) {
...
if (paid > total) {
...
event.preventDefault();
}
There are some conditions missed:
empty input field
not a number
In order to convert a string to number you can prefix the string with a plus sign.
A solution could be:
$("#mainform").on('submit', function(e) {
var total = +$("#gtotal").val();
var paid = +$("#paid").val();
if (($("#gtotal").val().trim().length == 0) || isNaN(total)) {
console.log("Please specify total");
$("#gtotal").focus();
e.preventDefault();
//
// stop function execution....
//
return;
}
if (($("#paid").val().trim().length == 0) || isNaN(paid)) {
console.log("Please specify paid");
$("#paid").focus();
e.preventDefault();
//
// stop function execution....
//
return;
}
if(paid > total) {
console.log("Amount can't be greater than total");
//
// prevent the submit action
//
re.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainform" action="http://www.google.com">
gtotal: <input id="gtotal" type="text">
paid:<input id="paid" type="text">
<input type="submit" value="Submit Form">
</form>
as an incoming javascript coder, i'm stuck at a sample exercise...
<script language="JavaScript">
var num1;
var messages;
var answer = document.getElementById("guess").value;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
function start() {
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("guess").value;
do {
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
if (num1 < answer) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
}
}
</script>
<body>
<form action="#">
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number" value="guess a number 1- 32">
</form>
</body>
this is supposed to print:
number of guesses is 5 or fewer: "either you know the secret or you got lucky"
Or number of guesses is 5 or more:"you should be able to do better"
Or number of guesses in 5 tries : "ahah!"
however it's not printing .../././
Initially there are few syntax errors to correct
do {} without while is not valid javascript.
start() is never called. I'm guessing you intended to use window.onload = start or <body onload="start();">
Your script is executed before the HTML elements it is modifying. If you want to access elements from the DOM you should access them within a function and/or place the script at the bottom of the body tag.
<script language="JavaScript"> is deprecated. I think you mean <script type="text/javascript"> although as that is the default the type is optional.
The messages variable is never assigned
You set text as the value to a number input. I suspect you intended to use placeholder="guess a number 1- 32". Note that placeholder is actually used to provide a hint about expected input. Direct instructions should use a label. This doesn't affect your javascript but is worth considering all the same.
Additionally myGuess() currently checks if the submitted value is less than the answer or more. You need to increment a count value and compare against that.
The below example do what you need
<form action="#">
<label for="inputfield">guess a number 1-32</label>
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number">
</form>
<p id="messages"></p>
<script type="text/javascript">
var num1;
var target = 5;
var messages = document.getElementById("messages");
var counter = 0;
var answer = Math.floor(1 + Math.random() * 32);
function start() {
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("inputfield").value;
if(num1 == answer) {
if (counter === target) {
messages.innerHTML = "Ahah!"
}
if (counter < target) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (counter > target) {
messages.innerHTML = "you should be able to do better";
}
} else {
counter++;
messages.innerHTML = "Keep trying";
}
}
window.onload = start;
</script>
<script language="JavaScript">
var num1;
var messages; // should be initialized inside start because at this moment it doen't exist
var answer;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
window.addEventListener("load", start); // on loading the page call start;
function start() {
messages = document.getElementById("message"); // this should be something
var button = document.getElementById("guessButton");
button.addEventListener("click", Myguess, false);
};
function Myguess() {
num1 = document.getElementById("inputfield").value; // the id is "inputfield" not "guess"
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
// else if to stop checking again (if is correct but not the best)
else if (num1 < answer) {
messages.textContent = "Either you know the secer or you got lucky!"; //textContent is better than innerHTML
}
// same here
else if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
}
</script>
<body>
<form action="#">
<input id="guessButton" type="button" value="guess">
<input id="inputfield" type="number" value="guess a number 1- 32">
</form>
<div id="message"></div>
</body>
Note: you was using do-while incorrectly (you was messing the while part). Anyway, do-while or any other loop will just loop forever if the answer is not correct because you are not letting the user to re-enter a number. What you need is to check whether the number is correct or not whenevr the user click the button (that parts you had it correct because you used the event listener).
What your code was doing (or supposed to be doing) is check if a user clicks the button and then loop if his answer was incorrect untill the answer is is correct (which is not going to happen because you never give the user another chance to enter a number again. He will get a chance after the function execution is finished. And because of the loop it will never be finished). It was never going to work because the loop waits for the user to enter another number (a correct one) to exit and the user is waiting for the loop to end to enter another number (see the paradox).
What it should do is to wait for the user to enter a number, check that number, prints the message accordingly for that number and then give the user to enter another number. (It is a loop (cycle) already so why need another loop)
The code you need is this:
<body>
<form id="form">
<input id="guessButton" type="submit" value="guess">
<input id="inputfield" type="number" placeholder="guess a number 1-32">
</form>
<div id="messages"></div>
<span id="counter"></span> tries
</body>
<script language="JavaScript">
document.getElementById('form').onsubmit = function() {
return Myguess();
};
var num1;
var messages = document.getElementById("messages");
var counterDiv = document.getElementById("counter");
counterDiv.innerHTML = 0;
var counter = 0;
answer = Math.floor(1 + Math.random() * 32);
function Myguess() {
num1 = document.getElementById("inputfield").value;
if (num1 == answer) {
messages.innerHTML = "Ahah!"
}
if (num1 < answer) {
messages.innerHTML = "Either you know the secer or you got lucky!";
}
if (num1 > answer) {
messages.innerHTML = "you should be able to do better";
}
counter++;
counterDiv.innerHTML = counter;
return false;
}
</script>
You can test it in this JSFiddle.
The function Myguess() is called when the form is submitted. There was no div messages missing in your code, so I added it. I also added the counter span which shows how many tries the player has had. Also the message "guess a number 1-32" is better added as placeholder. I hope that was helpful !
Programming a simple web page but when i use JavaScript alert and prompt boxes I am randomly directed to another screen that says "file not found" This happens when I use the enter key to say "ok"on the Java Script prompt box and anytime I just click on the okay for the alert box. How can I fix this? why is this happening?
HTML code
<!DOCTYPE html>
<html>
<title>BasketBall Game</title>
<link href ="styles.css" rel = "stylesheet" type ="text/css">
<script type = "text/javascript" src = myScript.js>
</script>
<body>
<div id = "mainbody">
<h1>BaksetBall Game</h1>
<form id="frm1" action="form_action.asp" onsubmit="play()">
<!--<label>Please Enter in Your Team Name:</label><input id="myInput" type="text" name="fname" size="20" autofocus placeholder="i.e. BYU" value ="" onkeydown = "if (event.keyCode == 13) document.getElementById('playButton').click()"><br>-->
<label>Please Enter in Your Team Name:</label><input id="myInput" type="text" name="fname" size="20" autofocus placeholder="i.e. BYU" value =""><br>
<!--<button id = "playButton" type = "submit" onclick="play()" value = "Play"> Play </button> -->
<button id = "playButton" type = "submit" >Play </button>
<button type = "button" onclick="reset()" value = "reset"> Reset</button><br>
</form>
<p id = "output"></p>
</div>
</body>
</html>
JAVASCRIPT CODE
//function that will go through and play games between user schools and other schools
function play()
{
//get user input on their team name
var x = document.getElementById("frm1");
//create a new object of type Team and initialize values
var userTeam = new Team(null, 0, 0);
//assign team name
userTeam.Name = x.elements[0].value;
//check to make sure the user enters in their team name
if (userTeam.Name == "")
{
window.alert("Please enter in a team name");
document.getElementById("myInput").select();
}
else
{
//initialize some variables
var oppTeam = null;
var games = null;
var homeScore = 0;
var visitScore =0;
//prompt for number of games to be played
games = prompt("Please enter in how many games you want to play");
//for loop to iterate through the games and keep track of userTeams wins and losses
for (var i =0; i < games; i++)
{
oppTeam = window.prompt("Please enter in an opposing team");
//while loop to check against ties
while(homeScore == visitScore)
{
//call to random function to get scores between 0 and 100
homeScore = getRandomInt(0,100);
visitScore = getRandomInt(0,100);
}
//determine who wins and who losses, and keep track of data
if(homeScore > visitScore)
{
userTeam.wins = userTeam.wins +1;
}
else
{
userTeam.losses = userTeam.losses +1;
}
}
//print out the results of the games
document.getElementById("output").innerHTML = userTeam.Name +" Wins: "+ userTeam.wins + " Losses:"+ userTeam.losses;
}
}
//function to get random numbers
function getRandomInt(min, max)
{
return Math.floor(Math.random() * (max - min)) + min;
}
//function to reset the game
function reset()
{
document.getElementById("output").innerHTML = " ";
document.getElementById("frm1").reset();
document.getElementById("myInput").select();
}
//function to create the Team "class"
function Team(Name, wins, losses)
{
this.Name = Name;
this.wins = wins;
this.losses = losses;
}
As stated in the comments:
The submit expects a server to handle your request. So for it to work you have to upload your project to a ASP.net development server or setup one locally.
I am trying to create a tip calculator using HTML and Javascript and each time the user changes the input field for the meal cost and tip amount, I have to validate whether or not it is a number and if it is, I have to cut down the number to 2 decimal places.
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = mealCost.toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = tipPercent.toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge);
var tipPercentage = document.getElementById(tipPercent);
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
I don't think it is taking the values that are edited using toFixed() and also the field tipAmount is showing NaN. How can I fix these errors?
<script>
function validateMealCost(mealCharge){
var mealCost = document.getElementById(mealCharge).value;
if (isNaN(mealCost)){
alert("The cost of the meal has to be a number.");
location.reload();
}
mealCost = parseInt(mealCost).toFixed(2);
return mealCost;
}
function validateTipPercent(tipPercent){
var tipPercent = document.getElementById(tipPercent).value;
if (isNaN(tipPercent)){
alert("The tip percentage has to be a number.");
location.reload();
}
if (tipPercent >= 1.0){
alert("You are very generous.");
}
tipPercent = parseInt(tipPercent).toFixed(2);
return tipPercent;
}
function calculateTipAmount(mealCharge, tipPercent){
var tipAmount;
var mealCost = document.getElementById(mealCharge).value;
var tipPercentage = document.getElementById(tipPercent).value;
tipAmount = mealCost * tipPercentage;
document.getElementById('tipAmount').value = tipAmount;
}
</script>
<input type="text" id="mealCharge" onchange="validateMealCost('mealCharge');" />
<input type="text" id="tipPercentage" onchange="validateTipPercent('tipPercentage');" />
<button onclick="calculateTipAmount('mealCharge','tipPercentage');">Calculate</button>
<input type="text" id="tipAmount" style="text-align: right;"/>
The validateMealCost and validateTipPercent functions lacked a parseInt to turn the values to numbers, and the calculateTipAmount function lacked a .value, turning it to NaN.
you need to parse the inputs - all the text inputs will provide strings and therefore cannot be compared to others numbers as a number not can they be in that form nor can they be used for calculations. Also note that even if you have used a number to do calculations, using .toFixed() will convert that number to a string.
For example - you will need to use parseInt or parseFloat which will return a number:
var tipPercent = parseInt(document.getElementById(tipPercent).value);
It is not updating because you need to declare the input before the script. So the simple fix for this would be to move the entire <script> tag to below the last occurrence of <input>.
You can emulate the result using the W3Schools Tryit Editor and pasting a snippet of your code:
<!DOCTYPE html>
<html>
<body>
The content of the body element is displayed in your browser.
<input type="text" id="tipAmount" />
<script>
document.getElementById('tipAmount').value = 5*5;
document.getElementById('tipAmount2').value = 5*5;
</script>
<input type="text" id="tipAmount2" />
</body>
</html>
Notice how the code only updates tipAmount and not tipAmount2.