rax313
rax313

Reputation: 88

Checkbox conditional validation in jQuery

I'm trying to make a form that validates 1 dropdown only if a checkbox is unchecked. I ended up with the following code:

HTML

<label for="chk">Checkbox</label>
    <input type="checkbox"  class="chk" ID="chkID" name="mychkBox" checked="checked" value="true"/>

<select ID="dropdownID" name="myDropdown" title="please select something">
    <option value="0">-Select-</option>
        <option value="1">-Option1-</option>
</select>

Javascript

$("#my-form").validate({
        rules: {
            myDropdown: {
                  required: "#chkID:unchecked",
                                  min:1
            }

        }//rules

});// end
$("#chkID").click(function() {          
      $("#dropdownID").valid();
      alert('gothere');
});

problem is it doesn't work, the form still submits. anyone know what I am missing/doing wrong?

-edit- Do I need to check for anything if the dropdown is being populated by JSON? will this work the dame way?. Reason I ask is that the form works as intended before any errors in validation but afterwards it requires the dropdown even if the checkbox is checked or unchecked. This is exactly what I am trying to do though...

-edit- Nevermind, I just hid/disabled the offending dropdown when the checkbox is checked so it will not validate

but I marked the answer "answered" since I forgot to mention about dynamically loaded content/HTML.

Upvotes: 0

Views: 2171

Answers (2)

Mike Mertsock
Mike Mertsock

Reputation: 12005

In your HTML markup your select element is named myDropdown, and in your jQuery code you refer to it as details. Try changing your validation config to:

rules: { myDropdown: { required: "#chkID:unchecked" } }

Edit

Also, your default option in the select element should have an empty value. Otherwise the required rule will always be satisfied:

<option value="">-Select-</option>

I created a jsFiddle that should accomplish what you need: http://jsfiddle.net/BGWbu/

Upvotes: 3

labroo
labroo

Reputation: 2961

I am not sure if there is a 'unchecked' selector, :S

try

"#chkID:not(:checked)"

also may be you need an if block, valid() returns boolean

if($("#dropdownID").valid()){
    alert('goThere');
}

Upvotes: 0

Related Questions