0

I'm trying to get the value of the current checkbox from a group of checkboxes with the same class name as below. However the jquery code seems to not be acting out accordingly. Could anyone help me out with this?

http://jsfiddle.net/m8fdc/2/

HTML

<input type="checkbox" class="checkbox1" value="test"/><br />
<input type="checkbox" class="checkbox1" value="test2"/> <br />
<input type="checkbox" class="checkbox1" value="test3"/> 

JS

$(document).ready(function() {
    //set initial state.

    $('.checkbox1').click(function() {
        if ($(this).is(':checked')) {
            console.log($('.checkbox1').val());
        }
    });
});

Any help would be greatly appreciated!

Thank you.

BaconJuice
  • 3,739
  • 13
  • 56
  • 88
  • 1
    You're already using `this`...so use it with `.val()`: `console.log($(this).val());` – Ian Jun 27 '14 at 18:06

3 Answers3

2

Is:

$('.checkbox1:checked').val()

What you are looking for?

jcaron
  • 17,302
  • 6
  • 32
  • 46
1

Try to use the this reference inside the click handler to get the value of the current element,

$('.checkbox1').click(function() {
    if ($(this).is(':checked')) {
        console.log(this.value);
    }
});

DEMO

And probably I would suggest you to use change event in this context rather than a click event. Also keep in mind that change event would get fired only when the checkbox turning into a checked state. Just decide which one would match your requirement.

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • Depending on when the OP wants this to execute, `click` is probably "better": http://stackoverflow.com/questions/5575338/what-the-difference-between-click-and-change-on-a-checkbox . If you think about what's expected for `change` events, IE following the spec makes sense but probably isn't desired. Using `click`, the handled is executed every time the checked state is toggled – Ian Jun 27 '14 at 18:12
-1

You are reading the value of the first .checkbox1 found if you do:

console.log($('.checkbox1').val());

When under the click event in jQuery you have direct access to the clicked node, so you can access it through the this.

You can either use the native property and do:

console.log(this.value);

or wrap it in jQuery to use jQuery's functions:

console.log($(this).val());
fmsf
  • 36,317
  • 49
  • 147
  • 195