-4

只有当 div 处于活动状态时,才应验证隐藏 div 下的内容。但在我的情况下,错误消息不适用于“大象”的情况。代码在http://jsfiddle.net/2eRsm/以获取更多详细信息,在此先感谢

<form>
   Choose your animal 
<select id="selectMenu">
    <option></option>
    <option value="monkey">Monkey</option>
    <option value="elephant">Elephant</option>    
</select>
<div class="mon">Monkey:
    <input type="text" class="required" name="mon"/> 
    <p id="error-msg">&nbsp;</p>
    </div>

<div class="ele">Elephant:
    <input type="text" class="required" name="ele"/>
     <p id="error-msg">&nbsp;</p>
    </div>
<button>submit</button>    
</form>
//js
$(document).ready(function () {    
       $("#selectMenu").bind("change", function () {
        if ($(this).val() == "monkey") {
            $(".mon").slideDown();
            $(".ele").slideUp();
        }
        else if($(this).val() =="elephant") {
            $(".ele").slideDown();
            $(".mon").slideUp();
        }
    });
});
$("button").click( function(){
    $("form").submit();   
});
$("form").validate({
    ignore:":hidden",
    rules: {
        name: ["mon", "ele"]
    },
    errorPlacement: function(error, element) {
        error.appendTo( $('#error-msg') )
    },
    invalidHandler: function(form, validator) {
        console.log( "error" );  
    },
    submitHandler: function( form ) {
        console.log( "no error" );
    }
});
//css
input {
    border: 1px solid #666;
    margin: 10px;
    padding: 3px; 
 }
p{
    display:inline;
    color: red;
}
.mon,.ele{
        display: none; 
}*
4

3 回答 3

4

2次ID不好:

 <p id="error-msg">&nbsp;</p>

做这个:

  <p class="error-msg">&nbsp;</p>

进而:

 error.appendTo( $('.error-msg') )

重置它:

   $("#selectMenu").bind("change", function () {
   $('.error-msg').html("");
于 2013-07-29T12:03:59.687 回答
0

Your validation works, but since you have two elements with ID "error-msg", I'd wager your error message gets attached to the first match, which is hidden when "Elephant" is selected.

于 2013-07-29T12:08:03.870 回答
0

您为错误消息使用了 2 次相同的 id ......使用不同的 id 试试这个...... http://jsfiddle.net/2eRsm/3/

<form>
   Choose your animal 
<select id="selectMenu">
    <option></option>
    <option value="monkey">Monkey</option>
    <option value="elephant">Elephant</option>    
</select>
<div class="mon">Monkey:
    <input type="text" class="required" name="mon"/> 
    <p id="error-msg">&nbsp;</p>
    </div>

<div class="ele">Elephant:
    <input type="text" class="required" name="ele"/>
     <p id="error-msg1">&nbsp;</p>
    </div>
<button>submit</button>    
</form>
于 2013-07-29T12:10:07.993 回答