This is a math practice game I am building that is using the random function to change the math problem numbers. The user will enter the answer into a text box and then check the answer by clicking the button called "check". The fillElements() function is working however i cannot get a response from the program when i click "check". I have sorted through a lot of mistakes thus far but this problem I can not see or understand.
<body onload="fillElements()">
<form action="math.html">
<ul>
<li id="num"> </li>
<li> +</li>
<li id="num2"> </li>
<li> =</li>
<li><input type="text" name="answer" id="answer" /></li>
</ul>
<button type="button" onclick="validate()">Check</button>
</form>
<script src="javaScript/math.JS"></script>
</body>
//JavaScript
var totalCorrect= 0;
var totalIncorrect= 0;
var score = math.round(totalCorrect/totalIncorrect);
var message= 'Congrats!, you scored:' + score + 'percent';
function fillElements() {
firstNum = ['0','1','2','3','4','5','6','7','8','9'];
secondNum = ['0','1','2','3','4','5','6','7','8','9'];
var rand= Math.floor((Math.random()*9)+1);
var rand2= Math.floor((Math.random()*9)+1);
var el= document.getElementById('num');
el.textContent = firstNum[rand];
var el2= document.getElementById('num2');
el2.textContent = secondNum[rand2];
}
function validate() {
var userAnswer= number(document.getElementById('answer'));
if (num + num2 === userAnswer) {
totalCorrect++;
alert(message);
fillElements();
}
else {
totalIncorrect++;
alert(message);
}
}
It's not number() it's Number()
Check here
Working code...
HTML
<form action="math.html">
<ul>
<li id="num"></li>
<li> +</li>
<li id="num2"></li>
<li> =</li>
<li><input type="text" name="answer" id="answer" /></li>
</ul>
<button type="button" onclick="validate();">Check</button>
</form>
Javascript
window.onload = function(){
fillElements();
}
function fillElements() {
firstNum = ['0','1','2','3','4','5','6','7','8','9'];
secondNum = ['0','1','2','3','4','5','6','7','8','9'];
var rand= Math.floor((Math.random()*9)+1);
var rand2= Math.floor((Math.random()*9)+1);
var el= document.getElementById('num');
el.textContent = firstNum[rand];
var el2= document.getElementById('num2');
el2.textContent = secondNum[rand2];
}
var totalCorrect= 1;
var totalIncorrect= 1;
function validate() {
var userAnswer= Number(document.getElementById('answer').value);
var num = document.getElementById('num').textContent;
var num2 = document.getElementById('num2').textContent;
var valid = Number(num) + Number(num2);
if (valid === userAnswer) {
totalCorrect++;
var score = Math.round(totalCorrect/totalIncorrect);
var message= 'Congrats!, you scored:' + score + 'percent';
alert(message);
fillElements();
}else {
totalIncorrect++;
var score = Math.round(totalCorrect/totalIncorrect);
var message= 'Congrats!, you scored:' + score + 'percent';
alert(message);
}
}
Edit: Don't use
var totalCorrect= 0;
var totalIncorrect= 0;
because if you score a point then it will print infinity => Math.round(1/0); try
var totalCorrect= 1;
var totalIncorrect= 1;
You've to get value of input to compare, not the input itself.
So replace the following
var userAnswer= number(document.getElementById('answer'));
with
var userAnswer= number(document.getElementById('answer').value);
Javascript is case sensetive, so you need to use Math.round, not math.round:
var score = Math.round(totalCorrect/totalIncorrect);
To use the variables later, you need to declare them outside the function:
var rand, rand2;
function fillElements() {
firstNum = ['0','1','2','3','4','5','6','7','8','9'];
secondNum = ['0','1','2','3','4','5','6','7','8','9'];
rand = Math.floor((Math.random()*9)+1);
rand2= Math.floor((Math.random()*9)+1);
var el= document.getElementById('num');
el.textContent = firstNum[rand];
var el2= document.getElementById('num2');
el2.textContent = secondNum[rand2];
}
To get the value from an input you need to use the value property. To convert it to a number you use Number, not number:
var userAnswer = Number(document.getElementById('answer').value);
To check the answer, use the variables that you set before. You haven't created any variables num and num2.
if (rand + rand2 === userAnswer) {
Related
Is there a function that splits the the given string into 2 evenly and place half of each to different textboxes?
I have tried var.split and var.slice
<script>
function display()
{
var myStr = document.getElementbyId("reqnum").value;
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
}
the expected should split the no. evenly and would display an error if the numbers are odd.
You can check the length of your input string. If it is odd then display an error.
<input type="text" id="reqnum" >
<input type="button" value="Display" onclick="display()">
<script>
function display()
{
var myStr = document.getElementById("reqnum").value;
if( !myStr || myStr.length % 2 == 1){
document.write("<p>Invalid input</p>");
}else{
var a = parseInt(myStr.substring(0, myStr.length/2));
var b = parseInt(myStr.substring(myStr.length/2, myStr.length));
document.write("<p>" + a + "</p>");
document.write("<p>" + b + "</p>");
document.write("<p> Result after multiplication : " + (a*b) + "</p>");
}
}
</script>
you can convert the numbers to string and then you can do the following.
var num = "1234567890"
var num1
var num2
if (num.length % 2 == 0) {
num1 = num.slice(0, (num.length / 2))
num2 = num.slice((num.length / 2))
} else {
console.log("Number contains odd number of digits")
}
console.log("Num1 " + num1 + " and Num2 " + num2)
use the Slice method, documentation is here.
For your slicing in half:
let half1, half2;
if( myStr.length % 2 == 0 ){
half1 = myStr.slice(0, (myStr.length / 2));
half2 = myStr.slice( (myStr.length / 2), myStr.length );
} else {
// error code
}
function splitToEqual(num){
num = num.toString()
return [num.substring(0, num.length / 2), num.substring(num.length / 2, num.length)]
}
console.log(splitToEqual(1234567890))
Have you tried using slice and length String methods?
Ie.
const string = '1234567890';
const length = string.length;
const res1 = string.slice(0,length/2);
const res2 = string.slice(length/2);
console.log(res1,res2);
Based on your request, I created the following piece of code :-)
Hope it helps.
var inputBox, warning, fBox, sBox;
function inputBoxChanged(e) {
var text = e.currentTarget.value;
if (text.length % 2 != 0) {
warning.innerText = "Value needs to be even sized";
fBox.value = "";
sBox.value = "";
} else {
warning.innerText = "";
var splitPos = text.length / 2;
fBox.value = text.slice(0, splitPos);
sBox.value = text.slice(splitPos, text.length);
}
}
document.addEventListener("DOMContentLoaded", function (e) {
inputBox = document.getElementById("input");
warning = document.getElementById("warning");
fBox = document.getElementById("first");
sBox = document.getElementById("second");
inputBox.addEventListener("change", inputBoxChanged);
});
<html>
<body>
<input id="input" type="text"/>
<span id="warning"></span>
<hr/>
<input id="first" type="text" readonly/>
<input id="second" type="text"readonly/>
</body>
</html>
Use substring() function as
var substring=string.substring(strating_index,end_index);
index will start from 0
var str="1234567890"
var substr=str.substring(0,str.length/2);
var substr2=str.substring(strlength/2,strlength);
$("#ID1").val(substr);
$('#ID2').val(substr2);
I am trying to call a function in this javascript code. My code needs to check for whether the user selects var num, var letters and var symbols to be true or false. In the code, I preset the values but I still search the object choices for the variables that are true and push it into the array choices_made. However, since I need to randomly choose the order in which the num, letters and symbols appear, I randomly choose the class based on the Math.random(). However, it doesn't show me the alert(jumbled_result) afterwards.
http://jsfiddle.net/bdaxtv2g/1/
HTML
<input id="num" type="text" placeholder="Enter desired length">
<br/><br/>
<input id="press" type="button" value="jumble it up">
JS
$(document).ready(function(){
var fns={};
$('#press').click(function(){
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
function gen(len, num, letters, sym){
var choices = {
1:num,
2:letters,
3:sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for(x in choices){
if(choices[x]==true){
choice_made.push(x);
}
}
for(i=0;i<len;i++){
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length-1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result){
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
});
You never declare functions within document.ready of jQuery. The functions should be declared during the first run(unless in special cases).
Here is a working code made out of your code. What I have done is just removed your functions out of document.ready event.
$(document).ready(function() {
$('#press').click(function() {
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
});
var fns = {};
function gen(len, num, letters, sym) {
var choices = {
1: num,
2: letters,
3: sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for (x in choices) {
if (choices[x] == true) {
choice_made.push(x);
}
}
for (i = 0; i < len; i++) {
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length - 1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result) {
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="num" type="text" placeholder="Enter desired length">
<br/>
<br/>
<input id="press" type="button" value="jumble it up">
Its because of the way the object choices have been intitialized.. Try this..
var choices = {
0:num,
1:letters,
2:sym
};
And also
var choice_made = [];
JS fiddle link : http://jsfiddle.net/8dw7nvr7/2/
Everything about the script works great right now unless there's a repeated letter in the word. If so, then it will only display the first of the letters. For example, if the random word is "look" it would display like this "lo k".
Unfortunately the only other related javascript hangman question here was for a script that didn't actually have issues on repeated letters. For reference: how to deal with repeated letters in a javascript hangman game. Can anyone help me get through the repeated letter issue? Thanks!
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-1.11.2.min.js"></script>
<script src="js/jquery-1.11.2.js"></script>
<link rel="stylesheet" href="css/main.css">
<title>Hang a Blue Devil</title>
</head>
<body>
<div class="wrapper">
<h1 class="title">Hangman</h1>
<h2 class="attempt-title">You have this many attempts left: </h2>
<ul class="hangman-word">
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
</ul>
<h3 class="hangman-letters"></h3>
<input class="text-value" type="text" maxlength="1" onchange="setGuess(this.value)">
<button class="text-button" onclick="checkGuess()"></button>
<p class="letters-guessed"></p>
</div>
</body>
<script src="js/hangman.js"></script>
</html>
My JS:
var hangmanWords = [
"the","of","and","a","to","in","is","you","that","it","he",
"was","for","on","are","as","with","his","they","I","at","be",
"this","have","from","or","one","had","by","word","but","not",
"what","all","were","we","when","your","can","said","there",
"use","an","each","which","she","do","how","their","if","will",
"up","other","about","out","many","then","them","these","so",
"some","her","would","make","like","him","into","time","has",
"look","two","more","write","go","see","number","no","way",
"could","people","my","than","first","water","been","call",
"who","oil","its","now","find","long","down","day","did","get",
"come","made","may","part"
];
// declared variables
var randomNumber = Math.floor(Math.random() * 100);
var randomWord = hangmanWords[randomNumber];
var underscoreCount = randomWord.length;
var underscoreArr = [];
var counter = randomWord.length +3;
var numberTest = 0;
var lettersGuessedArr = [];
var lettersGuessedClass = document.querySelector('.letters-guessed');
var li = document.getElementsByClassName('tester');
var textValue = document.querySelector('.text-value');
var attemptTitle = document.querySelector('.attempt-title');
var hangmanWordClass = document.querySelector('.hangman-word');
var hangmanLettersClass = document.querySelector('.hangman-letters');
// actions
attemptTitle.innerHTML = "You have this many attempts left: " + counter;
console.log(randomWord);
function setGuess(guess) {
personGuess = guess;
}
for (i=0;i<underscoreCount;i+=1) {
underscoreArr.push("_ ");
underscoreArr.join(" ");
var underscoreArrString = underscoreArr.toString();
var underscoreArrEdited = underscoreArrString.replace(/,/g," ");
hangmanLettersClass.innerHTML = underscoreArrEdited;
}
function pushGuess () {
lettersGuessedArr.push(personGuess);
var lettersGuessedArrString = lettersGuessedArr.toString();
var lettersGuessedArrEdited = lettersGuessedArrString.replace(/,/g," ");
lettersGuessedClass.innerHTML = lettersGuessedArrEdited;
}
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
i += 20;
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
};
My bin:
http://jsbin.com/dawewiyipe/4/edit
You had a stray bit of code that didn't belong:
i += 20;
I took it out, and the problem went away (the loop was intended to check each character, the +=20 broke the process of checking each character)
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
}
http://jsbin.com/noxiqefaji/1/edit
What I'm trying to do is have 2 text boxes that connect to one button. When the button is clicked, it calls a function to parse the 2 text box entries and then perform an addition (2 seperate functions). Can anybody point out what I'm missing on this? I keep getting num1 as undefined when I call it in the console.
<!DOCTYPE html>
<html>
<head>
<title>.</title>
</head>
<body>
Number1: <input type='text' id='num1'><br>
Number2: <input type='text' id='num2'><br>
<br>
<button onclick='add()'>Add</button>
<div id='toUser'></div>
<script>
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
function parsing()
{
var num1mod = parseFloat($('n1')).value;
var num2mod = parseFloat($('n2')).value;
if (isNaN(num1mod || num2mod))
{
user.innerHTML = ('Please enter a valid number');
}
else
{
add();
}
}
function add()
{
parsing();
return num1mod + num2mod;
user.innerHTML = (return)
}
</script>
</body>
</html>
Try this,
function parsing()
{
var user = document.getElementById('toUser');
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;
var num1mod = parseFloat(n1);
var num2mod = parseFloat(n2);
if (!isNaN(n1) || !isNaN(n2))
{
user.innerHTML = 'Please enter a valid number';
}else{
var total = num1mod + num2mod;
user.innerHTML = total;
}
return false;
}
There are a few problems with this code:
$('num1') appears to be jQuery or some other library. From the tags though it doesn't look like you are using jQuery.
If you are using jQuery, $('num1') is an invalid selector. It should be $('#num1')
If you are using jQuery, it should be .val() rather than .value and it should be inside the preceding parenthesis ($('#num1').val()), not outside.
Native JavaScript:
var num1mod = parseFloat(n1, 10);
var num2mod = parseFloat(n2, 10);
jQuery:
var num1mod = parseFloat($('#num1').val(), 10);
var num2mod = parseFloat($('#num2').val(), 10);
Problem is the following. Each time, when button "Dodaj" is pressed an item is added to list in html. I need to show a total cost of items on separate element; in my case I used hidden input. I tried by declaring a global variable for total price in function for adding, and then read it in function Izracunaj. However, no value is displayed in hidden input.
Code:
<script type="text/javascript">
var total= 0;
function AddItem()
{
var startingPrice= document.getElementById('cena').value;
var numbers= /^\d+$/;
//Preverimo, če so kot cena vnešena samo števila
if(startingPrice.match(numbers))
{
if(startingPrice< 10)
{
//Preberemo vrednosti iz vnosnih polj
var productName= document.getElementById('productName').value;
var price= document.getElementById('price').value;
//Regularni izraz za validacijo imena
var letters= /^[a-zA-Z]+$/;
if(!imeIzdelka.match(letters))
{
alert("Napačen vnos imena. Vnašate lahko samo črke.");
}
else
{
//Pridobimo seznam in ustvarimo nov element seznama
var list= document.getElementById('list');
var product= document.createElement('li');
var fullName= productName+ " - " + price+ "€";
//Novemu elementu določimo vrednost
product.innerHTML = fullName;
//Vstavimo element
list.insertBefore(product, list.firstChild);
_price = parseFloat(price);
total= total+ _price;
}
}
else if(startingPrice> 10)
{
//Preberemo vrednosti iz vnosnih polj
var productName= document.getElementById('productName').value;
var price= document.getElementById('price').value;
var letters= /^[a-zA-Z]+$/;
if(!productName.match(letters))
{
alert("Napačen vnos imena. Vnašate lahko samo črke.");
}
else
{
//Pridobimo seznam in ustvarimo nov element seznama
var list= document.getElementById('list');
var product= document.createElement('li');
//Spremenimo barvo na rdečo
product.style.color = "red";
//Združimo vrednosti
var fullName= productName + " - " + price+ "€";
//Novemu elementu določimo vrednost
product.innerHTML = fullName;
//Vstavimo element
list.insertBefore(product, list.firstChild);
_price = parseFloat(price);
total= total+ _price;
}
}
}
else
{
alert("Kot ceno lahko vnašate samo cela števila.");
}
//Vrnemo skupno ceno
return total;
}
</script>
<script type="text/javascript">
Function Calculate()
{
var price = AddItem();
document.getElementById('totalPrice').value= price;
}
</script>
I am sorry for code not being in english language.
Here are the inputs:
<input type="button" id="add" value="Add Item" onClick = AddItem() />
<input type="button" id="calculate" value="Calculate" onClick = Calculate() />
<input type="hidden" id="totalPrice" />
hidden inputs use value not innerHTML
document.getElementById('skupnaCena').innerHTML = cena;
need to be
document.getElementById('skupnaCena').value = cena;
You also need to cobvert strings to numbers using parseFloat() before you add them.
I solved the problem. The problem was, that I was trying to display the total price in "input type = hidden". I changed it to text with readonly attribute, and it works.