JQuery validation-select required if checkbox checked
Asked Answered
G

5

39

using jquery I want to make a selection from a select box required (ie it can't be left as the blank default) if a particular checkbox is ticked. My code:

$(document).ready(function(){
  $("#myForm").validate({
    rules: {
      myDropDown: {
        required: {       
          depends: function(element) {
            return $("#myCheckbox:checked")
          }
        }
      }
    }
  })
})

The html:

<input type="checkbox" name="myCheckbox" id="myCheckbox" value="1">
<select name="myDropDown" id="myDropDown">
  <option value="" selected></option>
  <option value="1">Choice 1</option>
  <option value="2">Choice 2</option>
  <option value="3">Choice 3</option>
</select>

Not only is the code not working it's throwing out the jquery tabs that I have as the next section of javascript.

Any advice appreciated.

Edit: Now that I've sorted out all my brackets the behaviour now is that it's making the select box a required field whether or not the checkbox is checked - ie the depends part is not working. Other javascript on the page is now working ok.

Gardner answered 4/7, 2011 at 15:33 Comment(1)
Sorry, I'm using jquery.validate.min.jsGardner
D
34

Please try like this

$(document).ready(function(){
  $("#myForm").validate({
    rules: {
       myDropDown:{
          required: function (element) {
             if($("#myCheckbox").is(':checked')){
                 var e = document.getElementById("myDropDown");
                 return e.options[e.selectedIndex].value=="" ;                            
             }
             else
             {
                 return false;
             }  
          }  
       }
    }
  });
});
Dost answered 5/7, 2011 at 5:1 Comment(2)
Hi, thanks but that still makes the dropdown required whether or not the checkbox is checked.Gardner
me edited the code.. please check it. added a return false in the else conditionDost
C
57

it should be able to work just like that:

rules : {
 myDropDown:{required:"#myCheckbox:checked"}
}
Capacity answered 6/3, 2014 at 15:2 Comment(3)
This does work, and is the standard method per the documentation: jqueryvalidation.org/category/methods/…Parturition
this is the most simplest answer, and therefore the better way.Lientery
This should be the checked answerExpiratory
D
34

Please try like this

$(document).ready(function(){
  $("#myForm").validate({
    rules: {
       myDropDown:{
          required: function (element) {
             if($("#myCheckbox").is(':checked')){
                 var e = document.getElementById("myDropDown");
                 return e.options[e.selectedIndex].value=="" ;                            
             }
             else
             {
                 return false;
             }  
          }  
       }
    }
  });
});
Dost answered 5/7, 2011 at 5:1 Comment(2)
Hi, thanks but that still makes the dropdown required whether or not the checkbox is checked.Gardner
me edited the code.. please check it. added a return false in the else conditionDost
T
8

This works like a charm

inputname:
{
    required: function(){
        if($("select[name=inputname]").val() == 1){
            return true;
        }
        else
        {
            return false;
        }
    }
}

You can edit the inputname to yours prefered.

To change it to input field, you can change the select part to input

Toadeater answered 7/10, 2011 at 7:38 Comment(3)
That could be compressed to required: function(){ return $("select[name=inputname]").val() == 1; }Flofloat
Or rather: required: function(){ return $("#elementID").val() === 1; }Picture
Per the documentation (jqueryvalidation.org/category/methods/…) the proper method to use is rules : { myDropDown: required:{"#myCheckbox:checked"}}Parturition
O
0

I don't know what plugin you are using, but

 return $("#myCheckbox:checked")

returns a Jquery object if your checkbox is checked. I think it would be more correct to do:

 return $("#myCheckbox").is(':checked')

which returns true or false.

Maybe this has nothing to to with your problem

Overseer answered 4/7, 2011 at 15:49 Comment(2)
The code is based on the second 'rules' example here: docs.jquery.com/Plugins/Validation/validate#toptionsGardner
Thanks, but changing the line you suggest allows no selection to be made when the checkbox is checked.Gardner
B
0
rules: {
    myDropDown: {
        required: function() {
            return $("input[id='checkbox']").val() == "1";
        }
    }
}

If the checkbox is checked here, it validates the myDropDown element.

OR

rules: {
    area1: {
        required: function() {
            return $("input[id='checkbox']").is(':checked');
        }
    },
    area2: {
        required: function() {
            return !$("input[id='checkbox']").is(':checked');
        }
    }
}

//return !$ or return $

both work fine..

Bonheur answered 8/2, 2023 at 21:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.