Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <code>onsubmit</code> action should be on the <code>form</code> and not on the <code>checkbox</code> field.</p> <p>Secondly, your <code>checkbox</code> element was assigned to variable <code>arrCheckboxes</code> whereas in the <code>if</code> loop you were checking with <code>checkb</code>. </p> <p>The modified code is as follows:</p> <p><strong>HTML:</strong></p> <pre><code>&lt;form name="deleteFiles" action="" method="post" onsubmit="return confirm_update();"&gt; &lt;input type='checkbox' name='files' id='1' value='1' /&gt;file 1 &lt;br&gt; &lt;input type="submit" value="Submit" name="submit"&gt; &lt;/form&gt; </code></pre> <p><strong>JS:</strong></p> <pre><code>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?"); } } </code></pre> <p><strong>EDIT:</strong> If in case your form has multiple <code>checkbox</code> 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:</p> <p><strong>HTML:</strong></p> <pre><code>&lt;form name="deleteFiles" action="" method="post" onsubmit="return confirm_update();"&gt; &lt;input type='checkbox' name='files' id='1' value='1' /&gt;file 1 &lt;input type='checkbox' name='files' id='2' value='2' /&gt;file 2 &lt;br&gt; &lt;input type="submit" value="Submit" name="submit"&gt; &lt;/form&gt; </code></pre> <p><strong>JS:</strong></p> <pre><code>function confirm_update() { var chkCount = 0; var arrCheckboxes = document.deleteFiles.elements["files"]; for (var i=0; i&lt;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?"); } } </code></pre> <p><a href="http://jsfiddle.net/hari_shanx/ZmMER/4/" rel="nofollow"><strong>Working Demo</strong></a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload