0

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.

Community
  • 1
  • 1
disruptive
  • 5,687
  • 15
  • 71
  • 135

2 Answers2

2

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?

Community
  • 1
  • 1
1

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

ptr
  • 3,292
  • 2
  • 24
  • 48