Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery add/remove required class for validation before form submission
    text
    copied!<p>I have a form with many fields in which two of these fields are <em>sort of</em> mutually exclusive, i.e. if one is empty the other <strong>must</strong> be present and the opposite is true (but they <strong>can</strong> be present at the same time). I have a simple validation check before submission which scans all fields with <code>class="required"</code> (no plugin), so i implemented the following code to perform validation of <strong>one field or the other</strong>:</p> <pre><code>$('#field1').keyup(function(){ if ($(this).val().length &gt; 0) { $('#field2').removeClass('required'); $(this).addClass('required'); } }); $('#field2').keyup(function(){ if ($(this).val().length &gt; 0) { $(this).addClass('required'); $('#field1').removeClass('required'); } }); </code></pre> <p>where <code>#field1</code> and <code>#field2</code> are the two mutually exclusive fields.</p> <p>I've checked with Firebug and the classes are correctly added/removed.</p> <p><strong>The problem is</strong>:</p> <p>if I trigger one or the other field, my form gets submitted <strong>even if other required fields are left blank</strong>. </p> <p>Validation code is:</p> <pre><code>$('form').submit(function(){ var fields = $('.validate'); var ret_value = true; $.each(fields, function(){ if ($(this).find('.required').val().length &lt; 1) { $(this).find('.errors').html('Campo obbligatorio!'); ret_value = false; } }); return ret_value; </code></pre> <p>});</p> <p>where a required input field's html is:</p> <pre><code>&lt;span class="validate"&gt; &lt;label for="field"&gt;Required Field&lt;/label&gt; &lt;input name="field" id="field" class="required"&gt; &lt;span class="errors"&gt;&lt;/span&gt; &lt;/span&gt; </code></pre> <p>Form validation performs correctly if I don't add/remove the <code>required</code> class with the code above.</p> <p>If i set a breakpoint in Firebug where I set</p> <pre><code>ret_value = false; </code></pre> <p>code gets executed, but for some reason it never gets to</p> <pre><code>return ret_value; </code></pre> <p>Also, inspecting the <code>fields</code> variable in Firebug I can see the correct entries.</p> <p>As I stated before, if I <strong>don't modify</strong> <code>#field1</code> and <code>#field2</code>, everything works correctly.</p> <p>What am I missing?</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