JQuery验证暂时删除所需的标记

时间:2014-05-08 16:20:53

标签: jquery html css asp.net-mvc

这是一个MVC项目,有几个文本框和一个复选框。取消选中时,需要所有文本框。选中时,其中一个文本框被禁用而不是必需的,而其他文本框仍然是必需的。红色边框和必需的错误消息不会随.rules("remove","required")消失我添加了一些CSS来更改边框的颜色,但我无法弄清楚如何摆脱错误消息。

模型视图

[Required(ErrorMessage="Required")]
public string textBox2{ get; set; }
[Required(ErrorMessage="Required")]
public string textBox3{ get; set; }

简明Razor HTML

@Html.CheckBoxFor(model => model.checkBox)
@Html.TextBoxFor(model => model.textBox1, new { @class = "disabledTrue" })
@Html.TextBoxFor(model => model.textBox2)
@Html.TextBoxFor(model => model.textBox3)

CSS禁用红色边框,将颜色更改为浅灰色

.disabledTrue.input-validation-error:disabled {
    border-color:lightgray;
}

JQuery的

$(document).ready(function () {
    $('#textBox1').rules("add", "required");

    $('#checkBox').click(function () {
        //makes the input unrequired
        $('#textBox1').rules("remove", "required");
    });
});

1 个答案:

答案 0 :(得分:0)

我最终使用了这个。很好地工作。选中该复选框后,将不再需要该复选框,并且不再显示必填文本。检查时,它是必需的,并显示必填文本。

$(document).ready(function () {
    $('#checkBox').click(function () {
        if ($('#checkBox').is(":checked")) {
            //makes the input unrequired
            $('#textBox1').rules("remove", "required");
             //I added .disableRequired to my HTML 
             // I found .field-validation-error with firebug
             $("span.disableRequired.field-validation-error").css("display", "none");
        }
        else{
            //makes the input unrequired
            $('#textBox1').rules("add", "required");
             //I added .disableRequired to my HTML 
             // I found .field-validation-error with firebug
             $("span.disableRequired.field-validation-error").css("display", "normal");
          }
    });
});