Reputation: 745
I have a simple function that is supposed to decrease the number inside a span of id "numactions" every time a button is clicked. What I'm missing is how to grab the value of the span id. I'm trying getElementById but that doesn't work.
<span id="numactions">5</span>
<button type="button" onClick="clickME()">Click me</button>
<script>
var clicks = document.getElementById("numactions");
function clickME() {
clicks -= 1;
document.getElementById("numactions").innerHTML = clicks;
}
</script>
Upvotes: 0
Views: 2612
Reputation: 9664
Your code has two issues.. first, this line:
var clicks = document.getElementById("numactions");
will grab the HTML element span
not the 5
, to get the content you should use .textContent
or .innerHTML
.
Second, using the above you'll get a "string" representation of the content, not a "number", so you'll need to use parseInt()
(1) to get a numeric value.
var clicks = parseInt(document.getElementById("numactions").textContent, 10);
function clickME() {
clicks -= 1;
document.getElementById("numactions").innerHTML = clicks;
}
<span id="numactions">5</span>
<button type="button" onClick="clickME()">Click me</button>
(1) It's highly recommended to use radix, the ,10)
part of the parseInt
in the answer, which here means decimal numeral system. Also, while using parseInt()
you get integers, for float you should use parseFloat()
instead.
Upvotes: 1
Reputation: 26
Here is the modified clickMe(), try this it will work
function clickME() {
var val= clicks.innerHTML;
val -= 1;
document.getElementById("numactions").innerHTML = val;
}
Upvotes: 0
Reputation: 46
Here is my working clickME function without JQuery
function clickME() {
var content = document.getElementById("numactions").innerHTML;
var intcontent = parseInt(content);
document.getElementById("numactions").innerHTML= intcontent -1;
}
Check the working demo here
Upvotes: 0
Reputation: 656
You need to fetch the innerHTML of numactions in order to get the original count. As it is a string, just parse using parseInt() fn and reduce the counter by one.
var clicks = document.getElementById("numactions");
function clickME() {
var counter = parseInt(clicks.innerHTML)-1;
document.getElementById("numactions").innerHTML = counter;
}
<span id="numactions">5</span>
<button type="button" onClick="clickME()">Click me</button>
Upvotes: 0
Reputation: 2848
You needed to parseInt to get the number in the span.
<span id="numactions">5</span>
<button type="button" onClick="clickME()">Click me</button>
<script>
var clicks = parseInt(document.getElementById("numactions").innerHTML) || 0;
function clickME() {
clicks -= 1;
document.getElementById("numactions").innerHTML = clicks;
}
</script>
https://jsfiddle.net/wh1qfkre/1/
Upvotes: 0
Reputation: 197
Try this:
var clicks = document.getElementById("numactions").innerHTML * 1;
function clickME() {
clicks -= 1;
document.getElementById("numactions").innerHTML = clicks;
}
Hope useful for you.
Upvotes: 0