1

This seems like a very simple thing to do, but I can't seem to get it to work. I have:

<button id="more">more</button>
<button id="less">less</button>

<p id="info"></p>

<script>
var howMany = 1;
$(#more).click(function(){
    howMany + 1;
});
$(#less).click(function(){
    howMany - 1;
});
$("#info").text(howMany);
</script>

I simply want the info paragraph to increase or decrease when the user click more or less.

1
  • howMany + 1; doesn't do anything. Commented May 29, 2012 at 19:54

4 Answers 4

5

You have several mistakes in your code, as others have already mentioned like missing quotes in selector, not reassigning variable value after incrementing/decementing.

var howMany = 1;
$('#more').click(function(){
    howMany += 1;
    $("#info").text(howMany);
});
$('#less').click(function(){
    howMany -= 1;
    $("#info").text(howMany);
});
$("#info").text(howMany);​

Here is a working Fiddle

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

Comments

4

There are several issues:

  • You need strings as selectors. So enclose #more with quotes: "#more".
  • You need to update the variable, not just calculate the addition or subtraction and ignore the result. Use += and -= instead of + and -.
  • You probably want to update the <p> element after every addition/subtraction. So put the .text call inside both click functions, after having updated the variable.

1 Comment

I saw the howMany + 1; but totally missed that the selector wasn't a string. Good eye!
1

You're not assigning the result to the variable, plus you're setting the text of the element outside the click event! Try:

$("#more").click(function(){
    howMany += 1;
    $("#info").text(howMany);
});
$("#less").click(function(){
    howMany -= 1;
    $("#info").text(howMany);
});

Comments

1

You add 1 to howMany, but don't affect the result to a variable. Use howMany = howMany + 1; or howMany += 1;

EDIT : according to pimvdb answer, ther're other problems, have a look on his post. Corrected code is here :

<button id="more">more</button>
<button id="less">less</button>

<p id="info"></p>

<script>
var howMany = 1;
$("#more").click(function(){
    howMany += 1;
    $("#info").text(howMany);
});
$("#less").click(function(){
    howMany -= 1;
    $("#info").text(howMany);
});
</script>

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.