0

I have a line of html

<p>Guess #<span id="count">0</span>!</p>

I need to write a function that will increment the number within the <span> tags by 1 each time the #guessButton is clicked. A simple .replaceWith() method wont work because that doesn't count. I'm assuming I need a for loop.

So far I've got this:

$("#guessButton").click(function() { addOne(); });

addOne() being the name of the function I will use to increment.

What javascript method can I use in the addOne() function to reference a number in the html and make it responsive?

4 Answers 4

1

Create a variable count and initialize it to zero. Then on every click, increment it and update the span by using the .html() or .text() method.

var count = 0;
$("#guessButton").click(function() {
    count++;
    $('#count').html(count);
});

Be sure to add your jquery to the end of the page or wrap it in a document ready handler.

Sign up to request clarification or add additional context in comments.

2 Comments

You mean the <script> tag with the link to the minified jquery file?
No, load jQuery at the head of your page. Load the code in my answer at the end of the page or wrapped in a document ready after jQuery.
0

another option would be to do it like this: https://jsfiddle.net/c259LrpL/39/

<button id="guessButton" type="button">guessButton</button>
<p>Guess #<span id="count">0</span>!</p>


<script>
$('#guessButton').click(function() {
    $('#count').html(function(i, val) { return val*1+1 });
});
</script>

1 Comment

Why add the parameter of "i" into the function? I don't see where you use it in the code block.
0

my simpleton answer for your review is here

<p>Guess #<span id="count">0</span>!</p>
<input type="button" id="guessButton" value="Guess" />

$("#guessButton").click(function() {
    var curCount = parseInt($("#count").text(), 10);
    $("#count").text(curCount + 1);
});

2 Comments

Hey thanks...im looking up the parseInt() method and it appears to take a string and turn it into an integer, is that right? Can you explain to me in more detail what is going on in your code? Why the ", 10"?
parseInt takes a string, and then the integer base that you want your int to be in. so the "10" in the line of code simply tells parseInt that you want a base-10 integer. @ColinAulds
0
function addOne() {
    $('#count').html(
        Number( $('#count').html() ) + 1
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.