Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery validation-select required if checkbox checked

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.

like image 632
Howard Shaw Avatar asked Jul 04 '11 15:07

Howard Shaw


3 Answers

it should be able to work just like that:

rules : {
 myDropDown:{required:"#myCheckbox:checked"}
}
like image 174
elle Avatar answered Oct 12 '22 07:10

elle


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;
             }  
          }  
       }
    }
  });
});
like image 34
Mahesh KP Avatar answered Oct 12 '22 08:10

Mahesh KP


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

like image 8
Koen den Braven Avatar answered Oct 12 '22 07:10

Koen den Braven