2

I'm trying to find an elegant solution without recourse to using JQuery or JS. Is there anyway that one can perform a select all on fields that are options in a model?

I'm not so keen to use: django checkbox select all

I've seen it hinted at: https://groups.google.com/forum/#!topic/django-users/dzdiZ9TLR5g

But never been able to find anything that would easily allow me to provide a select all directly from Django. Does anyone know if this is possible to switch on? Or is JS the only way to perform this?

I note this answer earlier: select all rows in django_tables2

But is there a way to avoid this approach because I may not know what why fields are - hence, if I have more than one field on each page - i.e. multiple names.

2 Answers 2

4

Here is my easy solution with multiple Forms and multiple Fields :

        {% for form in formset %}

    <div>
        {% for field in form %}

        {{ field }}

        {% for check in field|slice:":1" %} 
        <input type="checkbox" onClick="toggle(this,'{{ check.name }}')"/>
        Select All
        {% endfor %}
        {% endfor %}
    </div>

    {% endfor %}

Each checkbox of one Field has the same name - so js can work with it. Note that all the fields of this example form are checkboxes.

JS Code :

<script type="text/javascript" >
function toggle(source,name) {
    checkboxes = document.getElementsByName(name);
    for (var i = 0,
        n = checkboxes.length; i < n; i++) {
        checkboxes[i].checked = source.checked;
    }
}
</script>

I extended this solution for django : How to implement "select all" check box in HTML?

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

Comments

2

Any solution you write within Django would involve overriding widget renders to output html that included javascript/jquery anyway. I don't think there is any getting round it.

Edit: to answer your comment, the way I would personally do it is create a SlaveCheckboxWidget that could do something as simple inherit from the standard checkbox widget but change the css class name to "slave-checkbox" or similar, then have a MasterCheckboxWidget that includes a bit of jquery to select all (".slave-checkbox") and toggle them.

More on customising django widgets here

1 Comment

Thanks - do you know of any good solutions that would handle multiple fields on each form?

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.