oran gilboa
oran gilboa

Reputation: 13

Button Clicks Counter

I have this jQuery code that count my button clicks, but for some reason it stops after only one click. Please help me fix it.

$(function() {
  $('.btn').click(function() {
    $(this).val(this.textContent + 1);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn" value="0">

Upvotes: 1

Views: 67

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

Use this.value to get the current value:

$(function() {
  $('.btn').click(function() {
    $(this).val(parseInt($(this).val()) + 1);
  });
});

Snippet:

$('.btn').click(function() {
  $(this).val(parseInt($(this).val()) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn" value="0">

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370589

Inputs generally do not have meaningful textContents - rather, they have values. To retrieve the current value from the button, either call .val() on a jQuery collection with that element, or access the plain element's .value.

Note that because .values are always strings, you'll also have to cast it to a number in order to add 1 to it properly, otherwise you'll concatenate:

$('.btn').click(function() {
  $(this).val(Number($(this).val()) + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn" value="0">

Upvotes: 0

Related Questions