根据复选框值动态添加和删除元素
我正在尝试动态地将textareas添加到表单中的div,具体取决于选中的复选框。 textareas作为
父元素中,因此它只是textareas的列表。 每当“CaseGrounds”复选框被选中时,我的JQuery都会添加textareas,但如果未选中相关复选框,我不确定如何删除相应的textareas。
我认为在添加textareas之前我会聪明并清空
- ,但是这会导致它只会添加1 textarea的问题,因为它会在复选框组的每次更改时清空元素。 另一个问题是,如果我取消选中然后重新检查一个复选框,它会一遍又一遍地添加textarea。
- Ground 1
- Ground 2
- Ground 3
这是JSFiddle: http : //jsfiddle.net/D5YP7/
这是我的HTML:
Step 2
Step 3
inheritance我的Jquery:
$('input[name="CaseGrounds"]').change(function () { $("#form-Step3 ol").empty(); //empty the ol within the div (#form-step3) within the form if ($(this).prop('checked')) { //which checkbox was checked if ($(this).val() == '1') { // if it was '1' then add the li below $("#form-Step3 ol").append(''); } if ($(this).val() == '2') { // if it was '2' then add the li below $("#form-Step3 ol").append(''); } if ($(this).val() == '3') { // if it was '3' then add the li below $("#form-Step3 ol").append(''); } } });
我无法逻辑地弄清楚如何编程我想要实现的目标。 有人可以帮我吗?
编辑:我原本应该提到我的textareas最终不会像“textarea1,textarea2,textarea3”那样整齐地命名等等。 他们最终将被命名为适合的任何内容,例如“投诉,评论,报告”。 我为过分简化代码道歉。
您可以根据复选框的值为li
指定一个id
,如果未选中则可以将其删除
$('input[name="CaseGrounds"]').change(function () { //$("#form-Step3 ol").empty(); //empty the ol within the div (#form-step3) within the form if ($(this).prop('checked')) { //which checkbox was checked if ($(this).val() == '1') { // if it was '1' then add the li below $("#form-Step3 ol").append(''); } if ($(this).val() == '2') { // if it was '2' then add the li below $("#form-Step3 ol").append(''); } if ($(this).val() == '3') { // if it was '3' then add the li below $("#form-Step3 ol").append(''); } } else { $('#li_'+$(this).val()).remove(); } });
小提琴
应该能够简化为这样的事情:
$('input[name="CaseGrounds"]').change(function () { var val = $(this).val(); if ($(this).prop('checked')) { //which checkbox was checked var txtArea = 'TxtArea' + val; $("#form-Step3 ol").append(''); } else { $('#TxtArea' + val).parent().remove() } });
DEMO
为什么要动态添加和删除所有DOM元素。 我宁愿隐藏并显示它们并默认将它们插入DOM( DEMO )。
在html中插入所有textareas:
默认隐藏它们:
#form-Step3 ol li { display: none; }
然后根据复选框显示和隐藏它们:
var textareas$ = $('#form-Step3 ol li'); $('input[name="CaseGrounds"]').change(function () { var elem$ = $(this); var correspelem$ = textareas$.eq(elem$.val() - 1); if(elem$.is(':checked')) correspelem$.show(); else correspelem$.hide(); });
我已经使用了复选框的数字,通过它在DOM中的位置来获取正确的文本框。 如果它们不总是匹配,则必须使用ID或其他内容。