我对web开发和html表单相对陌生。在我的网络应用程序中,我有一个列表(gpstracks),每个列表条目都有一个复选框,这样用户就可以编辑、删除、下载等等。。。同时选择所有曲目。为了提高可用性,我想添加一个"全选"按钮或复选框,它可以自动检查表单中的所有其他复选框(最好不用重新加载整个表单)。
有可能这样做吗?我一直在尝试使用
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($tracks){
$form = $event->getForm();
foreach($tracks as $track)
{
$form->get($track->getId())->setData(array('checked'=>true));
}
}
与"提交"类型的第二个按钮组合使用,该按钮显示为"全选"。显然,这会重新加载整个表单。但在重新加载后,所有复选框都保持未选中状态,因此setData方法似乎根本没有效果。
是否有任何选项可以通过编程方式选中表单中的复选框复选框,最好是在不重新加载整个表单的情况下?
使用jquery:
// cerad.js
Cerad = {};
Cerad.checkboxAll = function(e)
{
var nameRoot = $(this).attr('name'); // "refSchedSearchData[ages][]";
nameRoot = nameRoot.substring(0,nameRoot.lastIndexOf('['));
var group = 'input[type=checkbox][name^="' + nameRoot + '"]';
var checked = $(this).prop('checked') ? true : false;
$(group).prop('checked', checked);
};
{# searchform.html.twig #}
{# form.dates is an array of form check boxes #}
{% if form.dates is defined %}
{% set items = form.dates %}
<td>{% include '@CeradGame/Project/Schedule/Twig/ScheduleSearchCheckboxes.html.twig' %}</td>
{% endif %}
{# ScheduleSearchCheckboxes.html.twig #}
{# render one set of check boxes as a table #}
{# Setting a class on the first item #}
<table border="1">
<tr><th colspan="30">{{ items.vars.label }}</th></tr>
<tr>
{% set itemFirst = true %}
{% for item in items %}
<td align="center">{{ form_label(item) }}<br />
{% if itemFirst %}
{{ form_widget(item, { 'attr': {'class': 'cerad-checkbox-all' }}) }}
{% set itemFirst = false %}
{% else %}
{{ form_widget(item) }}
{% endif %}
</td>
{% endfor %}
<tr>
</table>
// Grab all the cerad-checkbox-all elements and pass to Cerad.checkboxAll
{% block javascripts %}
<script type="text/javascript">
$(document).ready(function()
{
// checkbox all functionality
$('.cerad-checkbox-all').change(Cerad.checkboxAll);
});
</script>
{% endblock %}
- 为复选框设置html类(在表单生成器中设置选项attr['class'])
- 使用其他类添加按钮
- 添加事件以捕获点击按钮2,并选中复选框http://www.sanwebe.com/2014/01/how-to-select-all-deselect-checkboxes-jquery