user3004356
user3004356

Reputation: 880

How to make two fields required based on the value of another non empty input field

I'm new to jQuery. I have to create a required field validating based on another non-empty field. Currently I have three fields - Country code , state code and residence.

AAA) If the residence number is not empty and the state code and country code is empty, it should show an error. This currently works for one field, but not the other field. How can I get working for the other field as well.

Code -

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
$( document ).ready(function() {
console.log("Hello1");
$("#step1").validate({   
       rules: {
        countrycode1: {
            required: {
        depends: function(element){
            return $("#residence").val()!="";
console.log("Hello5");
        }
    }
        }           
    }

});
});</script>
</head>
<body>
<form id="step1" action="#" method="post">
    <label>Country Code</label>
    <input type="text" id="countrycode1" name="countrycode1" value="91"/>
</br>
    <label>Std Code</label>
    <input type="text" name="stdcode" id="stdcode" value="80"/>
</br>
    <label>Residence</label>
    <input type="text" name="residence" id="residence" />
</br>
    <input id="submit" type="submit" value="next step" name="submit"/>
</form>
</body>
</html>

FIDDLE

Upvotes: 0

Views: 1234

Answers (2)

mayank chaturvedi
mayank chaturvedi

Reputation: 182

use this DEMO

 $('#submit').click(function(){

if($('#residence').val()!='')
{

    if($('#countrycode1').val()!="91" && $('#countrycode1').val()!='')
    {

       if($('#stdcode').val()=="80" ||$('#stdcode').val()=='')
       {

          $('#stdcode').next().text( "this Field is Required" );

       }
    }else if($('#stdcode').val()!="80" && $('#stdcode').val()!='')
    {
       if($('#countrycode1').val()=="91" ||$('#countrycode1').val()=='')
       {
           $('#countrycode1').next().text( "this Field is Required" );
       }
    }


}

});

Upvotes: 1

tragiclifestories
tragiclifestories

Reputation: 88

You've only set rules for the one field. You'll need to have another property on rules for stdcode.

Upvotes: 0

Related Questions