2011-01-11 78 views
0

我有一组记录以表格形式显示在表单中。在每个记录有一个删除复选框 - 在这里用的是简体格式形式:删除确认

<form method="post" action="" id="update-history-form"> 
    Item 1 <input type="checkbox" value="1" name="History[0][delete]"> 
    Item 2 <input type="checkbox" value="1" name="History[1][delete]"> 
    Item 3 <input type="checkbox" value="1" name="History[2][delete]"> 

    <input type="submit" value="Update History" name="update"> 
</form> 

输入“name”属性的整数值有助于确定哪些记录已经被选中删除。

我想要的是如果任何删除复选框被选中(提交时),就会显示JavaScript警报确认。

回答

2
$('#update-history-form').submit(function(){ 
    if ($(this).find('input:checkbox:checked').length){ 
    return confirm("Really delete any of them?"); 
    } 
}); 

这将取消用户的表单提交不确认确认对话框。

如果您的表单中有非删除复选框,您可能需要将选择器修改为仅限那些名称为contains“删除”的输入,例如,

$(this).find('input[name*="delete"]:checked') 
+0

谢谢,这个作品pefrect。很快就会接受答案。 – GSTAR 2011-01-11 18:26:11

0

使用jQuery:

$('#update-history-form').submit(function(ev) { 
    ev.preventDefault(); 
    if (this.find("input:checkbox:checked").length == 0 || confirm("Are you sure?")) this.submit(); 
}); 
0
<form method="post" action="" id="update-history-form" onsubmit='return confirmChecks(this);'> 
    Item 1 <input type="checkbox" value="1" name="History[0][delete]"> 
    Item 2 <input type="checkbox" value="1" name="History[1][delete]"> 
    Item 3 <input type="checkbox" value="1" name="History[2][delete]"> 

    <input type="submit" value="Update History" name="update"> 
</form> 
<script type='text/javascript'> 
function confirmChecks(someForm) { 
    var inputList = someForm.getElementsByTagName('input'); 
    var aCheckboxIsChecked = false; 
    for (var i=0; i < inputList.length; i++) { 
    if (inputList[i].type.toLowerCase() == 'checkbox' && inputList[i].checked) { 
     aCheckboxIsChecked = true; 
     break; 
    } 
    } 

    if (aCheckboxIsChecked) { 
    var proceed = confirm('Really delete those things?'); 
    if (!proceed) { 
     return false; 
    } 
    } 
    return true; 
} 
</script>