pfdsppp
pfdsppp

Reputation: 13

Count number of clicks on radio button

I have group of radio buttons like this: <form> <input class="answer" name="answer" value="10" type="radio">ans0<br> <input class="answer" name="answer" value="11" type="radio">ans1<br> </form> And I have place on page where I write how many times did you click on any radio button.

<p>Clicked:</p> <p id="clicked">0</p>

I need jquery to count all those clicks. Can you help me?

Upvotes: 0

Views: 2854

Answers (4)

Scott Selby
Scott Selby

Reputation: 9580

Here is of a working example on jsFiddle , I put an extra attribute in the radio box html to store the number of clicks. If this is an option for you I think it makes for effecient clean code , then there is only one block of code written to handle the click event and display clicks for every radio button - no matter how many you may have

<input class="answer" name="answer" value="10" type="radio" data-clicked="0">ans0<br>
<input class="answer" name="answer" value="11" type="radio" data-clicked="0">ans1<br>​

$(function(){
    $('.answer').click(function(){
       var numOfClicks = $(this).attr('data-clicked');
       numOfClicks = (numOfClicks * 1) + 1;
       $(this).attr('data-clicked', numOfClicks);
       alert(numOfClicks);
    });    
});​

Upvotes: 0

qooplmao
qooplmao

Reputation: 17759

Try..

$(function(){
    var clicked = 0,
        radios = $('form input[type="radio"]'),
        clickBlock = $('#clicked');

    radios.click(function(){
        clicked++;
        clickBlock.html(clicked);
    });
});​

Upvotes: 0

Christofer Eliasson
Christofer Eliasson

Reputation: 33875

Attach a click-event listener to your radio buttons. Then in the callback you read the current number in the element with id clicked, you parse it into a number, add 1, and write the new value to the element.

Something like this:

// Attach a click-event listener to your radio-buttons​
$("input[type='radio']")​.on("click", function () {
    // Cache the element
    var elm = $("#clicked");
    // Read the current value
    var count = parseInt(elm.text(), 10);
    // Update the element with the new value
    elm.text(count + 1);    
});​​​​​​​​

DEMO

Upvotes: 1

micha
micha

Reputation: 49612

You can use the click function to capture clicks.

var counter = 0
$('input[name=answer]').click(function() {
  counter++
  $('#clicked').text(counter); // update text
});

Upvotes: 0

Related Questions