Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango form submit button's onclick does not call JavaScript function
    primarykey
    data
    text
    <p>I have a Django form that needs to do some client-side validation before submitting the form. This is the code in the template:</p> <pre><code>&lt;form action="/{{ blog_entry.id }}/addComment/" method="post"&gt; {{ commentForm.name.label_tag }} {{ commentForm.name }} &lt;span id="spanNameReq" style="color:Red; display:none;"&gt;Required&lt;/span&gt; &lt;br /&gt; {{ commentForm.email.label_tag }} {{ commentForm.email }} &lt;span id="spanEmailReq" style="color:Red; display:none;"&gt;Required&lt;/span&gt; &lt;span id="spanEmailInvalid" style="color:Red; display:none;"&gt;Invalid e-mail address&lt;/span&gt; &lt;br /&gt; {{ commentForm.website.label_tag }} {{ commentForm.website }} &lt;span id="spanWebsiteInvalid" style="color:Red; display:none;"&gt;Invalid URL&lt;/span&gt; &lt;br /&gt; {{ commentForm.comment.label_tag }} &lt;span id="spanCommentReq" style="color:Red; display:none;"&gt;Required&lt;/span&gt; &lt;br /&gt; {{ commentForm.comment }} &lt;br /&gt; &lt;input type="submit" value="Add comment" onclick="javascript:var ret = validateComment(); return ret;" /&gt; &lt;/form&gt; </code></pre> <p>But the problem is that validateComment does not get called at all, and the form gets submitted straight away. Strangely enough if I replace the onclick event with</p> <pre><code>javascript:alert('test'); </code></pre> <p>or</p> <pre><code>javascript:return false; </code></pre> <p>that JS code gets executed fine (and in the second case it won't submit the form).</p> <p>Why does it not execute the function I specified? Just to confirm that I have included the script file in the HTML head (including the JS code embedded in the template does not make a difference), and if I don't use a Django form, but a normal HTML form it works fine.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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