0

I have this html

<input type="checkbox" name="mycheck[]" value="1" />
<input type="checkbox" name="mycheck[]" value="2" />
<input type="checkbox" name="mycheck[]" value="3" />

If I have this jQuery code:

$('input[name="mycheck"]').change(function() {
    alert("which checkbox index I checked");
}

Assuming the indexes are 0 based I should have 0, 1, 2 How do I get it to alert "1" when I click the middle checkbox?

0

4 Answers 4

2

Try this:

  $("input[name='mycheck[]']").change(function() {
        alert($(this).index());
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks.. I tried this but didn't keep the brackets. I see it works with brackets
2

There is an .index() method for that

$('input').change(function() {
    alert($(this).index());
});

http://jsfiddle.net/6UfV7/

1 Comment

hmm I'm sure I tried this.. but I think I was using the core name and not the name with the brackets.. thx I'll try it again.
2

Use the .index() method.

$('input[name="mycheck[]"]').change(function() {
    var index = $('input[name="mycheck[]"]').index(this);
    alert(index);
});

But you also need to target mycheck[] instead of mycheck as that is how you have named your elements.

Demo at http://jsfiddle.net/gaby/K9CF2/1/

1 Comment

Yea.. I realize now I was missing the brackets when I tried this last. Thanks
0

Asuming the numbers go like 1,2,3,4, and so on, you could simply do that:

alert($(this).val()-1);

or that:

alert($(this).index());

And also, you have to select the entire name:

$('input[name="mycheck[]"]')

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.