0

I would like to know how to use jQuery to save the names of selected options from a Django based multiple checkbox? It seems like I was not be able to select the group of checkbox... Can someone give me suggestions on my code? Thanks!

jsfiddle example

HTML code

<table class="tab_model">
    <tbody>
        <tr>
            <th>
                <label for="id_model_0">Model:</label>
            </th>
            <td>
                <ul>
                    <li>
                        <label for="id_model_0">
                            <input type="checkbox" name="model" value="A" id="id_model_0">Model A</label>
                    </li>
                    <li>
                        <label for="id_model_1">
                            <input type="checkbox" name="model" value="B" id="id_model_1">Model B</label>
                    </li>
                    <li>
                        <label for="id_model_2">
                            <input type="checkbox" name="model" value="C" id="id_model_2">Model C</label>
                    </li>
                </ul>
            </td>
        </tr>
    </tbody>
</table>
<input class="submit" type="submit" value="Submit">

jQuery

var allVals = [];

$('.submit').click(function () {
    $('input[id^="id_model_"] :checked').each(function () {
        allVals.push($(this).val());
    });
    alert(allVals);
});
3
  • $('input[name="model"]')? Commented Aug 19, 2013 at 16:44
  • Figured it out. I think an extra space ` :checked` kills the jQuery... Commented Aug 19, 2013 at 16:58
  • @Ariane your approach also works after removing the space. Thanks! Commented Aug 19, 2013 at 16:58

1 Answer 1

1

I would give those boxes a class, something like class='the_checkboxes' Then use:

$(".the_checkboxes:checkbox:checked").each(function()({
    allVals.push($(this).val());
});

It will be cleaner (to me, anyway).

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

3 Comments

I agree. Since this multiple checkbox is built from Django, I need to add another jQuery statement to add a class. Thanks!
Well that might not work, then. Since the classes may not be part of the DOM yet. Why can't you add the class from Django? Are you not using a template?
Yes. I am using a Django template. Of course, I can overwrite the existed template to add a class.

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.