0

When I click button .one I want .res value to + 1 but it doesnt seem to work

$(".one").click(function(){
    $('.res').val() + 1;
})
<input class="res" src="0">
<button class="one">1</button>
2
  • .val gets the value - don't think the src attribute is valid for an input (unless it is an image input) Commented Aug 29, 2019 at 9:16
  • Firstly, you're using the getter, not the setter. See the docs: api.jquery.com/val. Secondly, the input should have value="0", not src="0" Commented Aug 29, 2019 at 9:17

3 Answers 3

2

You're not saving the value back into $('.res'). Also note that you need to use parseInt (or possibly parseFloat) to convert the string value to a number, and you should set the initial value of $('.res') with value, not src:

$(".one").click(function(){
    $('.res').val(parseInt($('.res').val()) + 1);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="res" value="0">
<button class="one">1</button>

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

3 Comments

Your script returns NaN
@stafilo in what situation?
My bad. Only tested by putting an actual value in there and pressing the button. Code and explanation corrected.
0

You need to save the value back to res.val - currently it's an orphaned expression:

$(".res").val(+($(".res").val()) + 1);

Comments

0

You're giving the <input> tag a src of 0 when it should be value:

<input class="res" value="0">

The jQuery is also syntactically incorrect, consider this instead:

var counter = $(".res").val();
$(".one").click(function(){
    counter++;
    $(".res").val(counter);
});

2 Comments

What happens if someone types a different number in to the input?
That would apply to any of the answers given. You could simply set the textbox to disabled="disabled" or readonly="readonly" in the HTML.

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.