如何根据另一个非空输入字段的值创建两个字段

时间:2014-05-30 12:27:41

标签: jquery html5

我是jQuery的新手。 我必须创建一个基于另一个非空字段验证的必填字段。 目前我有三个字段 - 国家代码,州代码和居住地。

AAA)如果住宅号不为空且状态代码和国家/地区代码为空,则应显示错误。这当前适用于一个字段,但不适用于其他字段。我怎样才能在其他领域工作。

代码 -

<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

2 个答案:

答案 0 :(得分:1)

使用此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" );
       }
    }


}

});

答案 1 :(得分:0)

您只为这一个字段设置了规则。您需要在stdcode规则上拥有另一个属性。