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?");
}
}
ワーキングデモ