Check If Checkbox Is Checked Before Deleting Confirm Message Using Javascript
I want to make sure that the users checked the checkbox before getting the delete confirmation message using javascript. Can someone please tell me how this can be made possible? F
Solution 1:
The onsubmit
action should be on the form
and not on the checkbox
field.
Secondly, your checkbox
element was assigned to variable arrCheckboxes
whereas in the if
loop you were checking with checkb
.
The modified code is as follows:
HTML:
<formname="deleteFiles"action=""method="post"onsubmit="return confirm_update();"><inputtype='checkbox'name='files'id='1'value='1' />file 1
<br><inputtype="submit"value="Submit"name="submit"></form>
JS:
functionconfirm_update() {
var arrCheckboxes = document.deleteFiles.elements["files"];
if (arrCheckboxes.checked != true) {
alert("You do not have any selected files to delete.");
returnfalse;
} else {
returnconfirm("Are you sure you want to proceed deleting the selected files?");
}
}
EDIT: If in case your form has multiple checkbox
fields and you want to throw error only when none of them is selected (which I think you want). You can do it like below:
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:
functionconfirm_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.");
returnfalse;
} else {
returnconfirm("Are you sure you want to proceed deleting the selected files?");
}
}
Post a Comment for "Check If Checkbox Is Checked Before Deleting Confirm Message Using Javascript"