Counter wont increment by decimals - javascript

I'm taking the plunge into javascript and have thus far have been relatively successful in what I've been trying to do. Although I realize that most of what I'm doing is probably being done incorrectly, or inefficiently.
For my first "project" I was trying to make a basic game. Click on the pickaxe, and it adds +1 to your total rocks. After you hit 5 rocks you can buy a shovel which will start generating rocks for you at a rate of one per second. I've currently had to set this to 1 per second as nothing under 1 seems to work.
My code (It's still somewhat messy as I've been tweaking it a lot):
JSBIN DEMO
HTML:
Total Rocks: <input id="txtNumber" type="text" value="0" onfocus="this.blur()" style=" border:none; text-align:center; background-color:transparent;" />
<br>
<img style="border:0;" src="http://img2.wikia.nocookie.net/__cb20130308043142/minecraftpocketedition/images/6/6d/Pickaxe_1.jpeg" onclick="javascript:add()">
<br>
Rocks per second: <input id="perSec" type="text" value="0" onfocus="this.blur()" style="width:30px; border:none; text-align:center; background-color:transparent;" />
<br>
Shovel(<input id="shovelCount" type="text" value="0" onfocus="this.blur()" style="width:20px; border:none; text-align:center; background-color:transparent;" />): 5 rocks
<input id="shovelBuy" type="button" value="Buy" onclick="javascript:shovel()"/>
</body>
Javascript:
var totalRocks = 0;
var rocksPerSec = 0;
function increment() {
var txtNumber = document.getElementById("txtNumber");
var newNumber = parseInt(txtNumber.value, 10) + rocksPerSec;
txtNumber.value = newNumber;
}
setInterval(function(){increment();}, 1000);
function add()
{
var txtNumber = document.getElementById("txtNumber");
var newNumber = parseInt(txtNumber.value, 10) + 1;
txtNumber.value = newNumber;
}
function shovel()
{
var txtNumber = document.getElementById("txtNumber");
var value = parseInt(txtNumber.value, 10);
if(value >= 5){
var newNumber = parseInt(txtNumber.value, 10) - 5;
txtNumber.value = newNumber;
var shovelCount = document.getElementById("shovelCount");
var newCount = parseInt(shovelCount.value, 10) + 1;
shovelCount.value = newCount;
rocksPerSec = rocksPerSec +1;
return false;
}
}
My Question: Why can't I increment the counter (rockPerSec) by a decimal value?

I made this fiddle..You basically had to replace parseInt() with parseFloat() and if you're asking "Why?", the answer is because if you want to increment the numeber of rocks by 0.2 for example, parseInt(0.2) is always 0. So you would always add 0.2 to 0 and parse it back to 0..Hope it helps..
var totalRocks = 0;
var rocksPerSec = 0;
function increment() {
var txtNumber = document.getElementById("txtNumber");
var newNumber = parseFloat(txtNumber.value, 10) + rocksPerSec;
txtNumber.value = newNumber;
}
setInterval(function(){increment();}, 1000);
function add()
{
var txtNumber = document.getElementById("txtNumber");
var newNumber = parseFloat(txtNumber.value, 10) + 1;
txtNumber.value = newNumber;
}
function shovel()
{
var txtNumber = document.getElementById("txtNumber");
var value = parseFloat(txtNumber.value, 10);
if(value >= 5){
var newNumber = parseInt(txtNumber.value, 10) - 5;
txtNumber.value = newNumber;
var shovelCount = document.getElementById("shovelCount");
var newCount = parseFloat(shovelCount.value, 10) + 1;
shovelCount.value = newCount;
rocksPerSec = rocksPerSec + 0.2;
return false;
}
}

As a help for your first project, i thought i show a suggestion of structuring code
jsfiddle: http://jsfiddle.net/j8CJS/
where you can start the code by using
var miner = new Miner();
miner.start();
it also allows resetting and stopping (or rather pauze) your current game. Your html code changes when relative properties are changed, and added some functions which i would normally borrow from jquery :)

Related

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

JS: How would I display a decrementing value through an html header? (and more)

Basically, I'm making a simple javascript/html webpage game where you guess a number and you have three chances to guess correctly. I'm having a problem displaying the number of attempts a player has left (It gets stuck at three). The color change that is supposed to occur also doesn't happen.
It also doesn't reset the page's display after a refresh (it takes 5 playthroughs of the game to get it to reset).
Maybe my for loop/if statement is screwy?
Here's my code.
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
The prompt is a blocking event, so you don't see the page update until after the prompts... try the example below, where setTimeout is used to allow a delay...
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
setTimeout(function() {
handleGuess(prompt("Try again!"));
},1000);//wait 1 second
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<br>
Attention. This is a fully workable example, and definitely an "overkill demo" for your "blocking" request.
I've removed the prompt calls with new inputs, and created 2 buttons for the game. One that calls the Start Game, and a second for the "in game try attemps".
I'm assuming you are still learning so this example might be helpful for you,by showing the advantages of separating your code into different elements, based on what they are doing, and also making it easier for you to "upgrade" the features of your game.
I could replace a lot more repeated code to make it look better, but that would not make it so familiar anymore to you.
/*function ChangeDif(Difficulty) {
var i = ""
if (Difficulty == 'easy'){
i = 10;
}
if (Difficulty == 'medium') {
i = 5;
}
if (Difficulty == 'hard') {
i = 3;
}
}
*/
var random = 0;
var start_chances = 3;
var start_attemps = 0;
var x = "";
function startgame() {
document.getElementById("start").hidden = true;
document.getElementById("number").hidden = false;
document.getElementById("again").hidden = false;
document.getElementById("demo").innerHTML = "Pick a number to win the game!";
random = Math.floor((Math.random() * 10) + 1);
//Cheat to see the random number, and make sure the game is working fine
//document.getElementById("cheater").innerHTML= random;
max_chances = start_chances;
step();
}
function lostAchance() {
max_chances--;
if (max_chances > 0) {
step();
} else {
loser();
}
}
function loser() {
//running out of turns
x = "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
endGame();
}
function step() {
var choice = parseInt(document.getElementById("number").value);
if (choice !== random) {
document.body.style.backgroundColor = "#CC0000";
x = "You have " + max_chances + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
document.getElementById("start").hidden = true;
} else {
//win
x = "You win! In " + (start_chances - max_chances) + " attemps <br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
endGame();
}
}
function endGame(){
document.getElementById("start").hidden = false;
document.getElementById("again").hidden = true;
document.getElementById("number").hidden = true;
}
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'easy')">Easy
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'medium')">Medium
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'hard')">Hard
<br>
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<input type="number" id="number" hidden />
<button type="submit" id="start" onclick="startgame()">Let's PLAY</button>
<button type="submit" id="again" hidden onclick="lostAchance()">Try Again</button>
<p id ="cheater"></p>
</body>
</html>

Checking answer in math game won't execute

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) {

Try to create basic math game

I'm doing a math game. I have this HTML/JavaScript code. It generates a random number but when I input the correct answer, it still displays 'wrong'. I'm not sure what went wrong.
Here is HTML code:
<table width="400" border="1" align="center">
<tr>
<td><div id="number1">1</div></td>
<td><div>+</div></td>
<td><div id="number2">2</div></td>
<td><div>=</div></td>
<td><input type="text"></input></td>
<td><input type="button" value="Check"></input></td>
</tr>
</table>
Here is my JavaScript code:
//random number appear when start game
var number1;
var number2;
number1 = Math.floor((Math.random() * 10) + 1);
number2 = Math.floor((Math.random() * 10) + 1);
document.getElementById("number1").innerHTML=number1;
document.getElementById("number2").innerHTML=number2;
//Answer
var answer = number1 + number2;
//add click handler with check answer
var checkAnswer = document.querySelector('input[type=text]');
var value = checkAnswer.value;
var btn = document.querySelector('input[type=button][value=Check]');
btn.onclick = function()
{
if (value == answer)
{
alert('You are correct');
}
else{
alert('You are incorrect, the answer was ' + answer);
}
document.querySelector('input[type=text]').value = "";
document.getElementById('number1').innerHTML = "";
document.getElementById('number2').innerHTML = "";
number1 = Math.floor((Math.random() * 10) + 1);
number2 = Math.floor((Math.random() * 10) + 1);
document.getElementById('number1').innerHTML = number1;
document.getElementById('number2').innerHTML = number2;
answer = number1 + number2
};
Move following lines in .onclick method.
var checkAnswer = document.querySelector('input[type=text]'); //needn't be moved in method
var value = checkAnswer.value;
You can verify the result from JSFiddle.
The problem was the variable value is initialize with empty string when you load the page, as when page is loaded the value is empty.
Compare answer to value in checkAnswer:
if (checkAnswer.value == answer) {
//correct
}else{
//incorrect
}
You don't update the value.
In the button click event update the value. JSFiddle.
btn.onclick = function()
{
value = checkAnswer.value;
...

adding a result of a calculation to a span with javascript after a button is clicked

Hi I'm new to javascript and I would like you to help me figure out why I can't get the result of the random number generator to appear in the span tag after the user clicks a calculate button using the min and max number they entered. I believe there is nothing wrong with the random number function it's just when I want to use the random number function as an event handler for the onclick event for the button it doesn't work. well, what I did was, I made a function called answer to gather the users input and to use that input as a parameter for the the random number function that is being called inside the answer function.
Then I used the answer function as an event handler for the onclick thinking that it would have the result of the the random number generator and would apply that to the onclick. and I stored that in var called storage so I could place the result of the event in the span tag later.
Here is the js fiddle of the code. can you help me solve my problem by getting the result of the random_number function in to the span $("output") after the button $("calculate") click?
only pure javascript, no jquery please.
Thank you in advance for your help. and I'm sorry if I got terminology wrong and for bad spelling. http://jsfiddle.net/jack2ky/WDyMd/
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
var storage = $("calculate").onclick = answer;
var answer = function(){
var miny = $("min").value;
var maxy = $("max").value;
return random_number(miny, maxy);
}
$("output").firstChild.nodeValue = storage;
}
</script>
</body>
</html>
var storage = $("calculate").onclick = answer;
...
$("output").firstChild.nodeValue = storage;
These two statements are called on page load. What is happening is you are changing the value of variable storage but the statement var storage = $("calculate").onclick = answer;
is being called only once when the page loads. You need to update the answer when user clicks the button. So you can remove $("output").firstChild.nodeValue = storage; and update the answer function like:
var answer = function(){
var miny = parseInt( $("min").value );
var maxy = parseInt( $("max").value );
var ans = random_number(miny, maxy);
$("output").innerHTML = ans;
}
This should do it:
<!DOCTYPE html>
<html>
<head>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
$("calculate").onclick = function() {
var miny = $("min").value;
var maxy = $("max").value;
$("output").firstChild.nodeValue = random_number(miny, maxy);
}
}
</script>
</head>
<body>
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
</body>
</html>
$("output").firstChild.nodeValue = storage;
This line seems to be the problem because your output-Element has no firstChild. So the value gets written nowhere.
Just use
> $("output").nodeValue = storage;
edit: Tested this in jsFiddle - this is not the solutions as mentioned below!
If You are able to get your value in the variable storage
then you can simply render this value in span as HTML
$("#output span").html = storage;

Categories

Resources