So, I'm trying to create a thing where you click a button and it pumps up the above number by 1.
My HTML code:
<center><span id="timesClicked">0</span></center>
<button type="button" class="btn btn-default" onclick="btnClick()">Click</button>
My JS code:
var mdb = {
"widgets": {
"amount":0
"stats": {
"timesClicked":0,
}
}
function btnClick(n){
mdb.widgets.amount += n;
mdb.stats.timesClicked += n;
return true
}
I don't really get how to link the number to the JS object though, can anyone help me?
So, I'm trying to create a thing where you click a button and it pumps up the above number by 1.
My HTML code:
<center><span id="timesClicked">0</span></center>
<button type="button" class="btn btn-default" onclick="btnClick()">Click</button>
My JS code:
var mdb = {
"widgets": {
"amount":0
"stats": {
"timesClicked":0,
}
}
function btnClick(n){
mdb.widgets.amount += n;
mdb.stats.timesClicked += n;
return true
}
I don't really get how to link the number to the JS object though, can anyone help me?
Share Improve this question edited Apr 15, 2018 at 12:43 Cœur 38.8k26 gold badges205 silver badges277 bronze badges asked Oct 13, 2013 at 15:54 LemedliLemedli 231 silver badge4 bronze badges4 Answers
Reset to default 2This may be over simplifying for you... I'm not sure what the object is needed for. Basically, you need to use this to update the timesClicked number in your HTML:
document.getElementById("timesClicked").innerHTML = timesClicked;
I've stripped out some of your object code so it's easier to work with. Here's the javascript I'm using:
Javascript
var timesClicked = 0;
function btnClick(){
timesClicked ++;
document.getElementById("timesClicked").innerHTML = timesClicked;
return true
}
DEMOS
http://codepen.io/anon/pen/FamJB
http://jsfiddle/xFgNk/1/
Try change btnClick(n)
to btnClick()
and change +=n
to ++
you are calling your function, with no argument n
:
<button type="button" class="btn btn-default" onclick="btnClick()">Click</button
you should call it with an argument like this:
<button type="button" class="btn btn-default" onclick="btnClick(1)">Click</button
the reason your code wont work is that when you call btnClick()
without n
inside n
will be undefined
and:
mdb.widgets.amount += n;
mdb.stats.timesClicked += n;
will be:
0 + undefined = NaN //(Not a Number).
Your code works, but it just does not increment with any value:) You need a default value for n otherwise it will add 0 every time:
so either do:
<center><span id="timesClicked">0</span></center>
<button type="button" class="btn btn-default" onclick="btnClick(1)">Click</button
(notice the btnClick(1) instead of btnClick())
or do:
function btnClick(n){
n = n || 1; // default value of n is 1
mdb.widgets.amount += n;
mdb.stats.timesClicked += n;
// if you want to update the value in the page (in the DOM):
document.getElementById('timesClicked').innerHTML = mdb.stats.timesClicked;
return true ;
}