Javascript if statement doesn't work as expected - javascript

I'm trying to create a small survey with a score. I want to make it so once user reaches score "4", it alerts some message. I wrote if statment for it, but for some reason it never alerts. But if I manually change score variable to 4, everything works as expected.
Where am I going wrong?
Here's the code:
http://jsfiddle.net/uy9kq9mx/
<script>
var score = 0;
function checkQuestionOne (){
var jautViens = document.getElementById('jaut1Pirm');
var jautDivi = document.getElementById('Jaut1Otra');
var jautTris = document.getElementById('Jaut1Tres');
var jautCetri = document.getElementById('Jaut1Cetu');
if(jautViens.checked) {
alert(++score)
}else if(jautDivi.checked || jautTris.checked || jautCetri.checked) {
alert("Nepareizi")
}else{
alert("Izvēlies opciju!")
}
}
if (score == 4){
alert(score);
}else{
}

You need to check the condition if the function
var score = 0;
function checkQuestionOne() {
var jautViens = document.getElementById('jaut1Pirm');
var jautDivi = document.getElementById('Jaut1Otra');
var jautTris = document.getElementById('Jaut1Tres');
var jautCetri = document.getElementById('Jaut1Cetu');
if (jautViens.checked) {
++score;
//since value of score is changed only in this block you can place the if block here
if (score == 4) {
alert('score is 4');
}
} else if (jautDivi.checked || jautTris.checked || jautCetri.checked) {
alert("Nepareizi")
} else {
alert("Izvēlies opciju!")
}
//keep the if block here, if there are multiple blocks in which the value of score is changed
}
<h1>Pirmais jautājums (1. pareizā)</h1>
<input type="radio" name="jaut1" id="jaut1Pirm" value="pirma" />Šī ir pirmā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Otra" value="otra" />Šī ir otrā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Tres" value="tresa" />Šī ir trešā atbilde
<br/>
<input type="radio" name="jaut1" id="Jaut1Cetu" value="ceturta" />Šī ir ceturtā atbilde
<br/>
<br/>
<button type="submit" onclick="checkQuestionOne();">Spied</button>
When you keep it outside of the function, the if condition is evaluated only once, but you need to check it everytime the value of score is changed.

Related

Trying to create a random game but doesn't seem to work

Under my form action, I called the textbox and buttons. It was suppose for the user to key in 2 values one being the highest value and another being the lowest value, it will then generate a random value between the lowest and the highest. The user will than guess the number if its correct it will print out the message correct
<form action="random" method="get" onSubmit="return validate()">
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()"><br/>
<br/><span id="numbers"></span>
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()">
<br/><span id="numbers1"></span>
<br/><input id="rand" type="submit" value="submit" onclick="Random()"><br/>
<input id="guess" type="text" value="Random Number Generator">
<br/>Enter your number<br/>
<input id="textbox" type="text"><br/>
<input id="guessing" type="button" value="Random" onclick="RandomNumber()"><br/>
<br/><span id="correct"></span>
</form>
My script consist of the methods and functions to use, I think the problem lies at the RandomNumber() function, im not sure where did I go wrong, but please assist me
function validate()
{
var values = document.getElementById("digit").value;
if(values<0)
{
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values && values >= 0)|| values.trim() == "")
{
document.getElementById("numbers").innerHTML = "Fill in a number";
return false;
}
else if (values>=0)
{
document.getElementById("numbers").innerHTML = "";
}
var values1 = document.getElementById("digit1").value;
if(values1<0)
{
document.getElementById("numbers1").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values1 && values1 >= 0)|| values1.trim() == "")
{
document.getElementById("numbers1").innerHTML = "Fill in a number";
return false;
}
else if (values >= values1)
{
document.getElementById("numbers1").innerHTML = "Highest number is smaller than lowest number";
return false;
}
else if (values1 > values)
{
document.getElementById("numbers1").innerHTML = "";
}
if((document.getElementById("digit").value>0) && (document.getElementById("digit1").value>0))
{
document.getElementById("rand").removeAttribute('disabled');
}
else
{
document.getElementById("rand").setAttribute('disabled', 'disabled');
}
}
This is the function to generate a random number in between the lowest number and the highest number.
function Random()
{
var value1 = document.getElementById("digit").value;
var value2 = document.getElementById("digit1").value;
minvalue= Math.ceil(value1);
maxvalue= Math.floor(value2);
var random = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
document.getElementById("guess").value=random;
}
And this is the part where I assume it may have cause the entire program to stop working, its after I wrote down this codes and my web page doesn't perform the way I want it to be.
function RandomNumber()
{
var value3 = document.getElementById("digit").value;
var value4 = document.getElementById("digit1").value;
minvalue= Math.ceil(value3);
maxvalue= Math.floor(value4);
var random1 = Math.floor(Math.random()*(maxvalue-minvalue)+1+minvalue);
var maxtries=5;
var counter=0;
var true=document.getElementById("textbox").value;
while(true!=random1)
{
document.getElementById("total").value=total;
counter +=1;
if(counter>maxtries)
{
document.getElementById("correct").innerHTML="No more tries"
}
if(true==random1)
{
document.getElementById("correct").innerHTML="Correct"
}
}
}
When I look at your code I see a couple of red flags.
E.g. true is a reserved keywoard in JS, you can't assign a value to it:
var true=document.getElementById("textbox").value;
This must throw an error in your development console.
Also in your loop while(true!=random1) neither true or random1 are reassigned, so if true in the beginning, the condition will never become false, hence the loop is never left in this case!
In general you should try to narrow your issue down, look at the errors and rather ask for help on smaller snippets where you ask concrete questions. With a statement like my web page doesn't perform the way I want it to be it is hard to provide help.

Coding beginner needing assistance

I'm brand new to coding. I've created a form with three fields- two with "number" types and one with radio button selection. I'm trying to utilize "try catch throw" to validate these fields and have error messages echoed onto the screen (not as an alert). I know that there is a lot of code in here, but I am really lost with this. Here is my HTML and js:
HTML:
<form>
<fieldset>
<label for="hshld" class="formhdr">Total number of people in your household:</label>
<input type="number" id="hshld" name="hshld" min="1">
</fieldset>
<fieldset>
<label for="hrrisk" class="formhdr">Number of high-risk people in your household:</label>
<input type="number" id="hrrisk" name="hrrisk" min="0">
</fieldset>
<fieldset>
<legend class="formhdr">Number of weeks in isolation:</legend>
<input type="radio" id="countone" name="headcount">
<label for="countone" class="numweeks">1</label>
<input type="radio" id="counttwo" name="headcount">
<label for="counttwo" class="numweeks">2</label>
<input type="radio" id="countthree" name="headcount">
<label for="countthree" class="numweeks">3</label>
<input type="radio" id="countfour" name="headcount">
<label for="countfour" class="numweeks">4+</label>
</fieldset>
<input type="submit" value="Submit" id="submit">
</form>
and my .js:
//Global variables
var hshld = document.getElementById("hshld");
var mysubmit = document.getElementById("submit");
var radioError = document.getElementById("radioError");
var weekCount;
//this function checks to see if the user entered a number into the field
function validatehshld() {
try {
if (hshld.value == "") {
throw "Enter a number!";
}
hshld.style.outline = "none";
// clear input box
}
catch (hshldError) {
hshld.style.outline = "2.5px dashed red";
hshld.placeholder = hshldError;
return false;
}
}
// makes sure that the radio button is selected. If not, throws an error message into the "radioError" paragraph at under the form.
function validatewkCount() {
try {
if (weekCount == 0) {
throw document.getElementById('radioError').innerHTML = "Select a number!";
}
// clear input box
hshld.style.outline = "none";
}
catch (weekCountError) {
radioError.style.outline = "2.5px dashed red";
radioError.placeholder = radioError;
return false;
}
}
// stop the form from submitting if a field needs attention
function endEvent() {
return event.preventDefault();
}
function validateSubmit() {
if(validatehshld() === false && validatewkCount() === false) {
endEvent();
}
}
// EventListeners, includes IE8 compatibility
if (hshld.addEventListener) {
hshld.addEventListener("focusout", validatehshld, false);
} else if (hshld.attachEvent) {
hshld.attachEvent("onclick", validatehshld);
}
// runs validateSubmit() function when the user clicks the submit button
if (mysubmit.addEventListener) {
mysubmit.addEventListener("click", validateSubmit, false);
} else if (mysubmit.attachEvent) {
mysubmit.attachEvent("onclick", validateSubmit);
}
if (mysubmit.addEventListener) {
mysubmit.addEventListener("click", numBottles, false);
} else if (mysubmit.attachEvent) {
mysubmit.attachEvent("onclick", numBottles);
}
// this function gets called via the onclick attribute (line 44)
function numBottles() {
// takes the current value of the input field from id "hshld"
var people = document.getElementById("hshld").value;
var hrrisk = document.getElementById("hrrisk").value;
// this variable represents the number of gallons a single person should have for one week of isolation- 1 gallon per day
var weekWater = 7;
// this variable will hold the number of weeks selected from the radio buttons
var weekCount;
// this code determines which radio button is selected and assigns a value to the variable depending on which radio button is selected
if (document.getElementById('countone').checked) {
var weekCount = 1;
} else if (document.getElementById('counttwo').checked) {
var weekCount = 2;
} else if (document.getElementById('countthree').checked) {
var weekCount = 3;
} else if (document.getElementById('countfour').checked) {
var weekCount = 4;
} else if (isNaN(weekCount) === true) {
var weekCount = 0;
}
// echo out the calculation (people X weekWater) to the span object with id=bottles
document.getElementById("bottles").innerHTML = (people * weekWater * weekCount) + (hrrisk * weekCount);
}
Try not to use try, catch, or throw here, instead create your error message in a new element and place it in the html somewhere you think it looks nice.
I would just use:
if (typeof hshld.value !== 'number') { // if a wrong data type was entered
document.getElementById("error-zone").innerHTML += "<div>Enter a number!</div"
} else {
// continue calculating answer
}
for the quick and dirty method.

I want to add a point when the if statement returns true

How can I add a point every time resu.html() is equal to "its a tie". I tried to write an if statement but it doesn't seem to work.
if(pl1.val() == result){
resu.html('its a tie');
resu.css({'left':'45.3%'});
}
//
if(pl1.val() == 1 && result == 2){
resu.html('Player 1 Wins the game');
resu.css({'left':'37%'});
} // That's how we have to get "its a tie" don't mind it
var resu = $('.result');
function pointCounter(){
var point = 1;
if(resu.html() == "its a tie"){
$('.point').html(point++);
}
}
$('button').click(pointCounter);
<p>You currently have <span class="point">1</span> Point</p>
<p class="result"></p>
<button>START</button>
Yes, you need to define point var outside the function.
<script>
var i = 0;
function buttonClick() {
document.getElementById('inc').value = ++i;
}
</script>
<button onclick="buttonClick()">Click Me</button>
<input type="text" id="inc" value="0"></input>

JavaScript with jQuery script not loading

My script with jQuery isn't loading, and when I press the calculate button it doesn't nothing (unsurprisingly.) I KNOW I copied and pasted jQuery in hard code into the file; this is intentional as I want the file to run offline as that's when I normally run it. Also it's intentional that I created the personal console as I normally work on this on a school laptop because that's when I'm bored and they've disabled the developer console.
It's not the jQuery that isn't loading though; I've been able to run it before.
I've tried checking the code, but to me it's just broken. Before the script didn't load, however, I think that somewhere there's an infinite loop because according to task manager, when the script loads and a calculate button is pressed the page freezes but the CPU is running like crazy. I have no idea what could be causing all of this, please help!
I know that other people have probably already done this and that there's probably many other better ways to do what I want to do, so just please remember that I'm doing this for fun, but I've been going at this in my spare time for quite a while an I haven't found anything so either I'm really dumb or the code is broken and it needs a rewrite.
It's supposed to increase the limit of the maximum number a language can understand by pushing the limit from something like 54 billion to 54 billion digits long. However, as stated in the summery, the script doesn't load.
<span id="console"></span>
<form>
<input type="radio" id="add" name="mathtype" checked="checked"> Addition (in devolopment)<br>
<input type="radio" id="sub" name="mathtype"> Subtraction (Unavailible)<br>
<input type="radio" id="multi" name="mathtype"> Multiplication (Unavailible)<br>
<input type="radio" id="div" name="mathtype"> Division (Unavailible)
</form>
<br>
Number: <input type="text" id="input1">
<br>
Number: <input type="text" id="input2">
<br>
<span id="extraInputs"></span>
<button id="addInput">Add another input field</button>
<br>
<button id="calc">Calculate...</button>
<br>
<br>
<p id="output">Press "Calculate..."</p>
<script>/*This is where I load the jQuery*/</script>
<script>
document.getElementById("console").innerHTML("<div class='info'>Script ran</div>");
"use strict";
$(document).ready(function(){
try {
var page = $("#console");
var log = function(message) {
page.append('<div class="log">'+message+'</div>');
};
var info = function(message) {
page.append('<div class="info">'+message+'</div>');
};
var warn = function(message) {
page.append('<div class="warn">'+message+'</div>');
};
var error = function(message) {
page.append('<div class="error">'+message+'</div>');
};
log("Doc and console up");
} catch(err) {
document.getElementById("console").innerHTML("<div class='error'>ERROR WITH LAUNCHING CONSOLE.</div>");
}
try {
var inputBoxes = 2;
var add = function(num1, num2) {
log("Running add");
var neg = [0, false, false];
num1 = num1.split("-");
num2 = num2.split("-");
log(num1);
log(num2);
if(num1.length == 2) {
num1 = num1[1];
neg[1] = true;
} else {
num1 = num1.toString();
}
if (num2.length == 2) {
num2 = num2[1];
neg[2] = true;
} else {
num2 = num2.toString();
}
log(num1);
log(num2);
info(neg);
var isNeg = false;
if(((neg[1] || neg[2]) && (neg[1]!=neg[2])) == true) {
isNeg = true;
}
log(neg);
num1 = num1.split('');
num2 = num2.split('');
log(num1);
log(num2);
var maxChar = Math.max(num1.length, num2.length);
log(maxChar);
if(maxChar > num1.length) {
for(var i=0;i<maxChar-num1.length;i++) {
num1.unshift("0");
}
} else if (maxChar > num2.length) {
for(var i=0;i<maxChar-num1.length;i++) {
num2.unshift("0");
}
}
var final = [];
var time;
var carry = 0;
for (var i=maxChar; i>0;i--) {
if(time != i++) {
carry = 0;
}
final[i] = (parseInt(num1[i]) + parseInt(num2[i]) + parseInt(carry)).toString();
if(parseInt(final[i]) > 9) {
var temp = final[i].split('');
final[i] = temp[1];
carry = temp[0];
time = i;
}
}
if(isNeg){
final.unshift("-");
}
info(final.join());
return final.join();
};
$("button#addInput").click(function(){
inputBoxes++;
$("#extraInputs").append('Number: <input type="text" id="input'+inputBoxes+'"><br>');
});
$("#calc").click(function(){
info("Checking conditions...");
if ($("#add").is(":checked")) {
info("Running...");
info($("#input1").val());
info($("#input2").val());
var final = add($("#input1").val(), $("#input2").val());
info("Ran");
if (inputBoxes > 2) {
info("inputBoxes: "+inputBoxes.toString());
for (var i=3; i<inputBoxes; i++) {
final = add(final, $("#input"+i.toString()).val());
}
}
info(final);
$("#output").text(final));
}
log("Functions up");
});
} catch(err) {
error(err);
}
});
</script>
It should take any amount of numbers and add them (as well as other things eventually), as long as the result's number of characters is less than or equal to the biggest number the language can understand.
I don't know what your code does, but you definitely have an infinite loop here:
for (var i=maxChar; i>0;i--) {
if(time != i++) {
carry = 0;
}
At each iteration, the for loop will decrease i by 1, but you are also increasing it by one, so it will keep the same value and the loop never ends. I imagine you actually wanted to check if (time != i+1).

Javascript - simple counting

This is my first post and second day with Javascript ;). I try to create a simple form, which:
Allows user put any letter / letters in an input field.
Than I want to send it to my script and:
a) check if anything was given in a form
b) if the user put any sign i want to put it in an array and count up the number of tries
c) if the number of tries reach 10 I want to to stop the script
My script doesn't remeber the number of tries. Moreover, it saves the data in an array but after the script is done it erases everything (I put some console.log() in the script, to see if it does anything). It looks like my variable count doesn't remember the number of tries :(.
How can I fix it ? - but in a simple way of coding :) (I don't want to do a lot of changes in my code)
<script type= "text/javascript">
var given_letters = []; // create an empty array
function givenLetter() {
var count = 0;
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
} else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
</script>
// in BODY section
<div>
<form><p>Put your letter here: <input type="text" id="letter" size="5" required><button onclick="givenLetter();">Send</button></p></form>
</div>
You can use given_letters.length instead of count, less code and its the same value, you need to use e.preventDefault(); so the form doesnt submit the form yet, here its a working example, for e.preventDefault(); to work you need to send the event in the button, like this:
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter(event);">Send</button></p>
</form>
</div>
the JS updated:
var given_letters = []; // create an empty array
function givenLetter(e) {
e.preventDefault();
var max_count = 10;
var letter = document.getElementById('letter').value;
while (given_letters.length <= max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(given_letters.length);//here is your count already
alert("OK");
return true;
}
}
while (given_letters.length === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
The default behaviour of a button in a form is to submit the form... and reload the page (quite stupid, IMO). This is why your script doesn't seem to remember anything. But there's a way to prevent that.
Also, write var count = 0; outside the function, otherwise it's being set to 0 every time the function is called.
var count = 0;
function givenLetter(event) {
event.preventDefault();
// ....
Try this.
Since the button i within the form tag the default behavior of button is submit. so the form will be submitted and reload the page. So to prevent that behavior we use event.preventDefault(); and make count as a global variable.
var given_letters = []; // create an empty array
var count = 0;
function givenLetter() {
event.preventDefault(); //to prevent reloading the page.
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter();">Send</button></p></form>
</div>

Categories

Resources