4

I am new to JavaScript / JQuery and I am not sure how I could do this. Maybe a small example of each part could help.

Say I have <div id="checkboxes"></div>

When the page loads, I will make an ajax call that will return JSON array. This I know how to do.

The objects will be like so:

[
  {
    name: "Item 1",
    id: "27",
    checked: "true"
  }
  ...
]

I need to somehow take that JSON response and inject in some checkboxes into that div that will also store the ID. The checkbox text would be 'name'.

Then, I need to know how to attach a function for when any of these checkboxes are checked, I will need to get the 'id' at that point because I will do an ajax call when any checked changes.

Any examples of doing this sort of thing with JQuery would be very helpful.

Thanks

1 Answer 1

6

Part 1 (creating the boxes):

$.each(json, function () {
    $("#checkboxes").append($("<label>").text(this.name).prepend(
        $("<input>").attr('type', 'checkbox').val(this.id)
           .prop('checked', this.checked)
    ));
});

Part 2 (dynamic fetching of ID):

$("#checkboxes").on('change', '[type=checkbox]', function () {
   //this is now the checkbox; this.value is the id.
});

http://jsfiddle.net/g2zaR/

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

3 Comments

How do I vertically align the checkbox label?
@Milo that is outside the scope of your question, but possibly with vertical-align: top|bottom|middle on the <input>.
Hey @ExplosionPills, how to build nested checkboxes if it contains child element as another checkbox?

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.