Note that there are some explanatory texts on larger screens.

plurals
  1. POJQuery add validation method to validate regarding another element in the form
    primarykey
    data
    text
    <p>I'm trying to create a custom validation method in JQuery and I can't manage to make it work properly.</p> <p>Here is what I want to do : </p> <pre><code>&lt;div class="row"&gt; &lt;label for="fld-stories"&gt;Stories&lt;/label&gt; &lt;select id="fld-stories" class="valid" name="stories" title=""&gt; &lt;option value=""&gt;--&lt;/option&gt; &lt;option value="1" label="1"&gt;1&lt;/option&gt; &lt;option value="2" label="2"&gt;2&lt;/option&gt; &lt;option value="3" label="3"&gt;3&lt;/option&gt; &lt;option value="4" label="4"&gt;4&lt;/option&gt; &lt;option value="5" label="5"&gt;5&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div id="row_master_bedroom_location" class="row"&gt; &lt;label for="fld-master_bedroom_location"&gt;Master Bedroom Location&lt;/label&gt; &lt;select id="fld-master_bedroom_location" name="master_bedroom_location" title=""&gt; &lt;option value="up"&gt;Upstairs&lt;/option&gt; &lt;option value="down"&gt;Downstairs&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>If the user selects the master bedroom location to be upstairs (see second select), the number of stories for the house should be superior or equal to 2 (which is logical since the master bedroom can't be upstairs if there is only one story).</p> <p>To do so I try to add a custom method to my JQuery validator :</p> <pre><code>$.validator.addMethod('masterBedroomLocation', function(value, element, params) { if (value == 'up' &amp;&amp; $("#fld-stories").val() &lt; 2){ return false; } }, 'You cannot select &amp;quot;Upstairs&amp;quot; for a one&amp;ndash;story home'); </code></pre> <p>I'm not sure how to get the value of another element in the form, I tried the JQuery old fashion way but it doesn't seem to work.</p> <p>For additional information, I add the custom method in a global javascript files, in a function that binds the JQuery validation to every forms that have a special class name.</p>
    singulars
    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.
 

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