Rashmi
Rashmi

Reputation: 551

Retrieving checkbox values with jQuery

I have following HTML:

<input type="checkbox" value="1"  class="trchoose">
<input type="checkbox" value="1"  class="trchoose">
<input type="checkbox" value="1"  class="trchoose">
<input type="checkbox" value="1"  class="trchoose">

​and following is my jQuery code:

jQuery('.trchoose').click(function() {
    alert('');
    res= jQuery(this).attr('class');
    alert(res);
});

Now I need to get value of the particular checkbox which was clicked. The above code of jQuery is not working.

What am I doing wrong?

Upvotes: 2

Views: 202

Answers (8)

webo
webo

Reputation: 133

If the HTML is being inserted into the DOM, you should use .on()

$('.trchoose').on('click', function() {
    alert($(this).val());
});

Upvotes: 0

Usman
Usman

Reputation: 3278

try this..

jQuery('.trchoose').click(function() {
         alert(jQuery(this).val());
});

Fiddle is here

Upvotes: 0

Database_Query
Database_Query

Reputation: 634

try this

function countChecked() {
  var n = $("input:checked").val();
     alert(n);
}
countChecked();
$(":checkbox").click(countChecked);

Upvotes: 0

Jashwant
Jashwant

Reputation: 29025

jQuery('.trchoose').click(function() {
    alert('');
    var res= this.value; // or jQuery(this).val() for jQuery version, but overhead.
    alert(res);
});

I assume that res is not a global variable.

Upvotes: 1

HungryCoder
HungryCoder

Reputation: 7616

It's simple.

<input type="checkbox" value="1"  class="trchoose">
<input type="checkbox" value="2"  class="trchoose">
<input type="checkbox" value="3"  class="trchoose">
<input type="checkbox" value="4"  class="trchoose">​

Please check, your second checkbox is not closed!

jQuery(document).ready(function(){
  $('.trchoose').click(function() {
    alert($(this).val());
  });​
})

Upvotes: 1

Habibillah
Habibillah

Reputation: 28705

try this:

jQuery('.trchoose').click(function() {
    alert('');
    var res= jQuery(this).val();
    alert(res);
});

Upvotes: 0

Blender
Blender

Reputation: 298562

Something like this should work:

$('.trchoose').on('change', function() {
    var value = $(this).val();
});​

Demo: http://jsfiddle.net/Blender/S4RVC/

Upvotes: 0

Danil Speransky
Danil Speransky

Reputation: 30473

Demo: http://jsfiddle.net/32VQ8/

jQuery(document).ready(function ($) {
  $('.trchoose').click(function() {
    alert($(this).val());
  });
});​

Upvotes: 0

Related Questions