2

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?

2
  • 1
    To get the value use this.value or $(this).val() plus you're missing var Commented Oct 1, 2012 at 4:11
  • Make sure you are using $(document).ready() Commented Oct 1, 2012 at 4:12

8 Answers 8

1
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.

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

Comments

1

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

Comments

0

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

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

Comments

0

Something like this should work:

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

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

1 Comment

yes, either one works, but this.value is 85% faster
0

try this:

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

Comments

0

try this

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

Comments

0

try this..

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

Fiddle is here

Comments

0

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

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

Comments

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.