stafilo
stafilo

Reputation: 83

Cant change input value with simple jquery

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>

Upvotes: 0

Views: 39

Answers (3)

Max Voisard
Max Voisard

Reputation: 1942

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);
});

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44087

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

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

Upvotes: 0

Nick
Nick

Reputation: 147146

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>

Upvotes: 2

Related Questions