jQuery Validate - 文本输入不断清除

时间:2013-02-03 01:24:15

标签: jquery textbox jquery-validate

如果取消选中该复选框并且文本框为空,则需要弹出验证消息。它会弹出但删除输入的文本,使其保持无效。我如何制作它,以便在输入第一个字符时验证消失,除非文本框为空,否则不会重新出现?

<form  id="practiceForm">
    <input type="text" name="firstName" id="textbox"/>
    <input type="checkbox" name="active" id="checkbox"/>
    <input type="submit" id="submit" value="Submit"/>
</form>

<script type="text/javascript">
    $('#checkbox').attr('checked', true);

    if($('#checkbox').attr('checked')){
        $('#textbox').attr('disabled', true);
        $('#textbox').val('');
    } else {
        $('#textbox').attr('disabled', false);
    };


$('#checkbox').change(function () {
    if($('#checkbox').attr('checked')){
        $('#textbox').attr('disabled', true);
        $('#textbox').val('');
    } else {
        $('#textbox').attr('disabled', false);
    };
});

$.validator.addMethod("textValidate", function(value){
    if(!$('#checkbox').attr('checked')){
        if(!$('#textbox').val('') || !$('#textbox').val(null)){

            return true;
        };
    };  
}, "If box is not checked then there must be text"
);


$('#practiceForm').validate({
    rules: {
        //textValidate: true
        firstName:{ 
                    textValidate: true
                    }
                }
            });

</script>

2 个答案:

答案 0 :(得分:2)

textValidate方法中的这个逻辑被破坏了:

if(!$('#textbox').val('') || !$('#textbox').val(null)){

您没有检查value ''null,而是设置为value。由于该方法是在每次键入事件时调用的,因此在键入时会消除输入。

请改为尝试:

$.validator.addMethod("textValidate", function (value) {
    if (!$('#checkbox').attr('checked')) {
        if (!$('#textbox').val() == '' || !$('#textbox').val() == null) {
             return true;
        };
    };
}, "If box is not checked then there must be text");

工作演示:http://jsfiddle.net/s2AjA/

附带问题:

您不需要大部分代码......

$('#checkbox').attr('checked', true);

if($('#checkbox').attr('checked')){
    $('#textbox').attr('disabled', true);
    $('#textbox').val('');
} else {
    $('#textbox').attr('disabled', false);
};

只有在DOM准备就绪时才运行一次,因为您将#checkbox设置为checked,看起来像if/then属性的checked条件完全是多余的&amp;不必要的。

可以更简单地编写如下。还使用prop更改了attr,这在使用jQuery 1.6 +时在技术上比attr更正确。

$('#checkbox').prop('checked', true);
$('#textbox').prop('disabled', true);
$('#textbox').val('');

答案 1 :(得分:0)

if(!$('#textbox').val('') || !$('#textbox').val(null)){

#textbox的值设置为“”然后为null,并使if语句始终返回false。

你可能意味着这样的事情:

if ($('#textbox').val() != '' || $('#textbox').val() != null) {