JQuery validation-select required if checkbox checked

后端 未结 4 569
北荒
北荒 2020-12-05 02:22

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:

$         


        
相关标签:
4条回答
  • 2020-12-05 02:57

    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

    0 讨论(0)
  • 2020-12-05 03:03

    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;
                         }  
                      }  
                   }
               }
      });
    });  
    
    0 讨论(0)
  • 2020-12-05 03:08

    it should be able to work just like that:

    rules : {
     myDropDown:{required:"#myCheckbox:checked"}
    }
    
    0 讨论(0)
  • 2020-12-05 03:18

    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

    0 讨论(0)
提交回复
热议问题