3

i have a form with lots of checkboxes.

the names and the number of checkboxes are created dynamically.

how can i get a jquery onClick event when i click on any of these checkboxes?

<form id="myform">
    <input type="checkbox" name="chk_123">
    <input type="checkbox" name="chk_456">
    <input type="checkbox" name="chk_23">
    <input type="checkbox" name="chk_3">
    <input type="checkbox" name="chk_443">
    <input type="checkbox" name="chk_6764">
</form>

i wish to select them using the form's id, in this example all checkboxes that belong to form #myform.

i ask this question because i don't wish to just add a class name to every checkbox and select by class name.

my goal: an alert box "you just clicked the checkbox with name chk_{whatever the number is}"

3 Answers 3

6

Use an attribute selector:

$('#myform input[type="checkbox"]').change(function() {
    alert("You just clicked checkbox with the name " + this.name)
});

Example fiddle

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

Comments

1

You can do:

$('#myform').on('change','input[type="checkbox"]',function() {
    alert('you just clicked the checkbox with name' + this.name);
});

2 Comments

Also note that you need to use event delegation with .on() since your input have been added dynamically to the DOM.
they are generated dynamically server side, i ll have this in mind if any client-side element addition happens :D
0

you can achieve it like follows:

$("#myform input:checkbox").change(function() {
    alert("you just clicked the checkbox with name "+ $(this).attr("name"));
});

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.