检查是否在使用javascript删除确认消息之前选中了复选框

时间:2013-09-18 11:26:53

标签: javascript

我想确保用户在使用javascript获取删除确认消息之前选中了复选框。有人可以告诉我这是如何实现的吗?

小提琴:

http://jsfiddle.net/ZmMER/

HTML

<form name="deleteFiles" action="" method="post" >
    <input type='checkbox' name='files' id='1' onsubmit="return confirm_update();" value='1' /> file 1<br>

    <input type="submit" value="Submit" name="submit">

</form>

的JavaScript

function confirm_update() {
    var arrCheckboxes = document.deleteFiles.elements["files"];
    if(checkb.checked != true) { 
        alert("You do not have any selected files to delete.");

    } else {
        return confirm("Are you sure you want to proceed deleting the selected   files?");
    }
}

1 个答案:

答案 0 :(得分:1)

onsubmit操作应该在form上,而不在checkbox字段上。

其次,您的checkbox元素已分配给变量arrCheckboxes,而在if循环中,您使用checkb进行了检查。

修改后的代码如下:

<强> HTML:

<form name="deleteFiles" action="" method="post" onsubmit="return confirm_update();">
    <input type='checkbox' name='files' id='1' value='1' />file 1
    <br>
    <input type="submit" value="Submit" name="submit">
</form>

<强> JS:

function confirm_update() {
    var arrCheckboxes = document.deleteFiles.elements["files"];
    if (arrCheckboxes.checked != true) {
        alert("You do not have any selected files to delete.");
        return false;

    } else {
        return confirm("Are you sure you want to proceed deleting the selected   files?");
    }
}

编辑:如果您的表单有多个checkbox字段,并且您希望仅在未选择任何字段时抛出错误(我认为您需要)。你可以这样做:

<强> HTML:

<form name="deleteFiles" action="" method="post" onsubmit="return confirm_update();">
    <input type='checkbox' name='files' id='1' value='1' />file 1
    <input type='checkbox' name='files' id='2' value='2' />file 2
    <br>
    <input type="submit" value="Submit" name="submit">
</form>

<强> JS:

function confirm_update() {
    var chkCount = 0;
    var arrCheckboxes = document.deleteFiles.elements["files"];
    for (var i=0; i<arrCheckboxes.length; i++) {
        if(arrCheckboxes[i].checked == true) {
            chkCount++;
        }
    }
    if (chkCount === 0) {
        alert("You do not have any selected files to delete.");
        return false;
    } else {
        return confirm("Are you sure you want to proceed deleting the selected   files?");
    }
}

Working Demo