While Loop Input Issue - javascript

I am trying to make a program that takes numbers from the user until they input a 0, the output how many positive and negative numbers were input, while also telling the user whether the number they input was positive, negative, or zero, however, when I use it, it crashes the webpage immediately if anything but a 0 is input. So I was wondering where this issue would be coming from and how I could resolve it.
JS:
var pos = 0;
var neg = 0;
var inp = 1;
function interpreter() {
while (inp != 0) {
inp = (document.getElementById("number"));
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML = pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML = neg + " negative numbers were inputted";
}
}
}
Where "number" is a text field for input, and the function is called upon the press of a button. Thanks in advance!

You're misunderstanding the event-processing nature of JavaScript.
If you have a while loop like that, you'll never yield control back to the browser itself, to handle user input, etc. You may be looking for something like this -- in addition to the removal of the explicit loop, note how the handling of inp has changed; previously you were comparing strings to numbers.
var pos = 0;
var neg = 0;
function interpret() {
var inp = parseInt(document.getElementById("number").value);
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML =
pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML =
neg + " negative numbers were inputted";
}
}
<form onsubmit="interpret();event.preventDefault()">
<input id="number">
<input type="submit" value="Interpret value">
</form>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>

If you really want my suggest:
var pos = 0
, neg = 0
;
document.forms['my-form'].addEventListener('submit',function(evt)
{
evt.preventDefault()
let inp = this.number.valueAsNumber
{
if (inp < 0)
{
this.out_1.textContent = 'Input is: negative'
neg++
}
else if (inp > 0)
{
this.out_1.textContent = 'Input is: positive'
pos++
}
else
{
this.out_1.textContent = 'Input is: zero';
this.out_2.textContent = pos + ' positive numbers were inputted'
this.out_3.textContent = neg + ' negative numbers were inputted'
}
}
})
label, button, output { display: block; margin:.4em; }
<form name="my-form">
<label>
Input:
<input name="number" type="number" min="-32768" max="32768" value="1">
</label>
<button type="submit"> enter </button>
<output name="out_1"></output>
<output name="out_2"></output>
<output name="out_3"></output>
</form>

Related

Page doesn't load when I set variable to 0 in Javascript

var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
while (attempts < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
while learning how to use a random number generator, I wantd to add a while loop and give 3 attempts to choose from a random number.
When I create a variable to set the number of attempts, if I make the variable equal to 0, my page doesn't load, but if I leave the variable empty without a value, the script doesn't run.
Any ideas of why this may be happening?
var randomNumber = Math.floor(Math.random() * 6);
var x = 0
var maximum = 3
while (x < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
Your while loop runs synchronously, during pageload. The script never finishes, because the while loop's condition is never negated, so control is never yielded back to the browser to repaint the page, so the user never has a chance to input a number or click on the button.
While you could keep using while by promisifying the onclick and awaiting a Promise, it'd be better to create the handler outside, once, and have it check if the attempts are maxed out.
You also need to use consistent variable names: either use x or attempts, not both:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
document.getElementById("submit").onclick = function() {
if (attempts >= maximum) return;
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
You could disable the button after the maximum number of attempts has been reached, like:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0;
var maximum = 3;
document.getElementById("submit").onclick = function(e) {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
if (attempts === maximum) e.target.disabled = true;
};
<input type="text" id="input" />
<button id="submit">Submit</button>

Guessing Game in Javascript

What I'm trying to do is make a simple guessing game where the user can any the number without limit but will be graded at the end when the guessed the number correctly based on the number of their guesses. However, with my code when I enter a number and press the button to multiple times the hint changes from "Higher" to "Lower" even if the number is not changed also the message that should be displayed when the number is guessed correctly is not showing. Here's my code, I'm a beginner so there's bound to be errors in the code and any help is appreciated.
<fieldset>
<input type="number" id="guess" />
<button onClick="checknum();">Check Number</button>
</fieldset>
<fieldset>
<p>Your current status:</p>
<output id="status_output">You have yet to guess anything.</output>
</fieldset>
<script type="text/javascript">
function checknum(){
var randomNumber = Math.floor((Math.random() * 100) + 1);
var guessNumber = document.getElementById("guess").value;
//var guessNumber = parseInt(guess.value);
var statusOutput = document.getElementById('status_output');
var counter = 0;
var isguessed = false;
do {
counter = (counter + 1)
if (guessNumber < randomNumber) {
statusOutput.value = ("Higher");
}
else if (guessNumber > randomNumber) {
statusOutput.value = ("Lower");
}
else if (guessNumber = randomNumber) {
set (isguessed = true());
statusOutput.value = ("Correct" + mark());
}
}
while (isguessed = false);
}
function mark(){
if (counter < 10){
statusOutput.value("Excellent");
}
else if (counter > 10 && counter <20){
statusOutput.value("Okay");
}
else
statusOutput.value("Needs Practice");
}
</script>
In your while you are assigning false to the variable named isguessed.
You want to do while (isguessed === false) instead. This will check if isguessed is set to false
isguessed = false : assigns the varibles isguessed to false
isguessed === false : a boolean expression return true or false

Javascript incrementing by more than one

var x1 = document.getElementById("x1");
var x2 = document.getElementById("x2");
function ThisEvent(){// needs a lot of work done to it
if (x1.value==1) {
x2.value--;
} else if (x1.value==2) {
x2.value++;
} else if (x1.value==3) {
x2.value+=5;
}
}
<input type="text" value="0" id="x1" onblur="ThisEvent()"> x1 </br>
<input type="text" value="0" id="x2"> x2
what is happening now is the digit is being added instead of incrementing when 3 is the input if x1. how do you make it increment by more than just one, without it being added it as a digit?
if (x1.value == 3) {
x2.value = parseInt(x2.value) + 5;
}
It's interpreting it as a string. You can parseInt the x2.value in the calculation.
The value of the input is a String, you need to convert it to a Number in order to perfom an addition on it.
You could do it like this:
function ThisEvent() { // needs a lot of work done to it
var valX1 = Number(x1.value);
var valX2 = Number(x2.value);
if (valX1 == 1) {
valX2--;
} else {
if (valX1 == 2) {
valX2++;
} else {
if (valX1 == 3) {
valX2 += 5;
}
}
}
x2.value = valX2;
}
jsFiddle: https://jsfiddle.net/v1utqv7f/

Javascript total return NaN for 4 digits num

Here is the javascript for calculating the price of the item the problem is that
whenever the price is 4 digits the value that return is NaN.
here's my hidden field for the price:
<input type="hidden" name="price" id="price"class="price" value="4500"readonly >
here's for my quantity field
<input type="number" name="quant" id="quant" value="2" />
here's for my shipment fee
<select id="shipment" onchange="myFunction3()" name="shipment2" disabled>
<option value="100" data-quantity="1">1 for 100 pesos </option>
</select
here's for the total price
<input type="text" id="demo" name="total_price" style="margin-top:10px;margin-left:5px;" readonly>
Script for changing the value of shipment
<script type="text/javascript">
document.getElementById('quant').addEventListener("keyup", function(){
var value = parseInt(this.value, 20),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
</script>
Calculating all the values
function myFunction3() {
var y= document.getElementById("shipment").value;
return y;
}
<script>
$("#price,#quant,#shipment").keyup(function () {
if(+myFunction3() =="" )
{
$('#demo').val(0);
}
else if($('#trigger')=="checked") //this is the problem
{
$('#demo').val($('#price').val() * $('#quant').val() ;
}
else
{
$('#demo').val($('#price').val() * $('#quant').val() + +myFunction3());
}
});
</script>
Not sure if this was just typed incorrectly in here, but you have a syntax error (missing closing parenthesis) near the problem area:
$('#demo').val($('#price').val() * $('#quant').val() ;
Should be:
$('#demo').val($('#price').val() * $('#quant').val());
I think it would be much better to ensure you aren't working with strings before you do math on them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
$('#demo').val(price * quantity);
You could go further and ensure that neither of them are NaN prior to working with them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
if(!isNaN(price) && !isNaN(quantity)) {
$('#demo').val(price * quantity);
} else {
alert('Please enter numbers only!');
}

Javascript error box

Hi guys I have this script here, which counts the characters and lines, now currently though it still allows lines and characters to go into minus, but I would like it to also put up a warning box so it stops the user from being able to put in more text, could you help me out?
javascript:
function textCounter(theField,theCharCounter,theLineCounter,maxChars,maxLines,maxPerLine) {
var strTemp = "";
var strLineCounter = 0;
var strCharCounter = 0;
for (var i = 0; i < theField.value.length; i++)
{
var strChar = theField.value.substring(i, i + 1);
if (strChar == '\n')
{
strTemp += strChar;
strCharCounter = 1;
strLineCounter += 1;
}
else if (strCharCounter == maxPerLine)
{
strTemp += '\n' + strChar;
strCharCounter = 1;
strLineCounter += 1;
}
else
{
strTemp += strChar;
strCharCounter ++;
}
}
theCharCounter.value = maxChars - strTemp.length;
theLineCounter.value = maxLines - strLineCounter;
}
and used in code:
<textarea name="comment" cols="50" rows="10" wrap="VIRTUAL" onKeyUp="textCounter(theForm.comment,theForm.remChars,remLines,900,30,50);"></textarea>
<br><input name=remChars type=text value="900" size=3 maxlength=3 readonly> characters left
<br><input name=remLines type=text value="30" size=3 maxlength=3 readonly> lines left<br>
Report to moder
1 - Add a check to the end of the function:
var check = strTemp.length <= maxChars && strLineCounter <= maxLines;
if (!check) alert("Error message here!");
2 - Trim the text of the field, so it contains only the needed chars:
theField.value = theField.value.sbustring(0, maxChars - 1);
3 - Add a return to the end of the function:
return check ;
4 - And change the event binding to:
onKeyUp="return textCounter(theForm.comment,theForm...

Categories

Resources