Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help with jquery validate plugin and checkboxes

I have a checkbox group that I need to name uniquely to store values in a database separately. However, using jquery validate plugin, I cannot validate the group with names being different.

<label>Would you like to compete?</label>
      <input type="checkbox"  name="compete1" value="2" class="competecheckbox" >
      <label for="compete_no">No</label>
      <input type="checkbox" name="compete2" value="1" class="competecheckbox">
      <label for="compete_yes">Yes</label>
      <div id="competeyes">
        <label class="competeyestxt" hidden=true>Which Location?</label>
        <textarea rows="4" cols="40" maxlength="2000" name="competeyestextarea" class="competeyestxt" hidden="true">
        </textarea>
      </div>

I tried adding

$.validator.addClassRules(
"competecheckbox", {required: true, minlength: 1});

This kinda works but it shows 2 error messages. One for each of the matching class 'competecheckbox'.

The problem is that even if the user selects compete1, the validation error message still remains for compete2.

How can I clear both messages when the user selects at least one checkbox?

thanks

like image 433
truthSeekr Avatar asked Dec 12 '22 10:12

truthSeekr


1 Answers

I ended up with something like this:

 <label>Would you like to compete?</label>
      <input type="checkbox"  name="compete[]" value="2" class="competecheckbox" >
      <label for="compete_no">No</label>
      <input type="checkbox" name="compete[]" value="1" class="competecheckbox">
      <label for="compete_yes">Yes</label>
      <div id="competeyes">
        <label class="competeyestxt" hidden=true>Which Location?</label>
        <textarea rows="4" cols="40" maxlength="2000" name="competeyestextarea" class="competeyestxt" hidden="true">
        </textarea>
      </div>


When the form is submitted you get values in an array as compete[1], compete[2] etc.
I didn't know that you could do an empty array for form variable names.
Every day I find out how ignorant I am :)

The validation rule would look like

$('#survey').validate( {
    rules: {
        "compete[]": {
            required: true,
            minlength: 1
        }
  });

The quotes around "compete[]" are required as explained here:

http://docs.jquery.com/Plugins/Validation/Reference#Fields_with_complex_names_.28brackets.2C_dots.29

like image 170
truthSeekr Avatar answered Jan 29 '23 05:01

truthSeekr