选择值后删除jquery验证错误消息

时间:2014-01-17 11:01:39

标签: javascript jquery twitter-bootstrap

使用bootstrap select插件和jQuery验证时遇到问题。当我选择值时,错误消息This field is required不会删除正常验证(没有引导程序选择插件)后选择值错误消息自动删除。如何解决这个问题?

JSFIDDLE

HTML:

<form id="myform"> <----With Select Plugin
    <select name="year" class="selectpicker">
        <option value="">Year</option>
        <option value="1">1955</option>
        <option value="2">1956</option>
    </select>
    <br/>
    <input type="submit" />
</form>
<form id="myform1"> <----Without Select Plugin
    <select name="fruit">
        <option value="">Year</option>
        <option value="1">1955</option>
        <option value="2">1956</option>
    </select>
    <br/>
    <input type="submit" />
</form>

JS:

$(document).ready(function () {
    $('.selectpicker').selectpicker();


    $('#myform').validate({ // initialize the plugin
        ignore: [],
        rules: {
            year: {
                required: true
            }
        },
        errorPlacement: function(error, element) {
            if (element.attr("name") == "year") {
              error.insertAfter(".bootstrap-select");
            } else {
              error.insertAfter(element);
            }
        },
        submitHandler: function (form) { // for demo
            alert('valid form submitted'); // for demo
            return false; // for demo
        }
    });
});
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform1" ).validate({
rules: {
fruit: {
required: true
}
}
});

2 个答案:

答案 0 :(得分:8)

您需要检查更改的有效性

$('.selectpicker').selectpicker().change(function(){
    $(this).valid()
});

演示:Fiddle

答案 1 :(得分:0)

试试这个

$('select').change(function(){
    if ($(this).val()!="")
    {
        $(this).valid();
    }
});

以下是Fiddle