0

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?");
    }
}
4

1 に答える 1

1

onsubmitアクションはフィールド上ではなく、フィールド上で行う必要がありformますcheckbox

第二に、あなたのcheckbox要素は variable に割り当てられまし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?");
    }
}

ワーキングデモ

于 2013-09-18T11:32:18.883 に答える