Best approach for extending unobtrusive javascript in MVC3 to add a style to a div client side

后端 未结 7 855
情话喂你
情话喂你 2021-01-31 03:50

I\'m using html5/Razor/MVC3 leveraging the Bootstrap template from Twitter. I want to have form validation that looks slick like they\'ve documented (http://twitter.github.com/b

7条回答
  •  臣服心动
    2021-01-31 04:23

    I needed to solve this using Bootstrap 3.1 and Razor. This is what I used:

    $.validator.setDefaults({
        highlight: function (element) {
            $(element).parents(".form-group").addClass("has-error");
        },
        unhighlight: function (element) {
            $(element).parents(".form-group").removeClass("has-error");
        }
    });
    
    $(function () {
    
        $('span.field-validation-valid, span.field-validation-error').each(function () {
            $(this).addClass('help-block');
        });
    
        $('form').submit(function () {
            if ($(this).valid()) {
                $(this).find('div.form-group').each(function () {
                    if ($(this).find('span.field-validation-error').length == 0) {
                        $(this).removeClass('has-error');
                    }
                });
            }
            else {
                $(this).find('div.form-group').each(function () {
                    if ($(this).find('span.field-validation-error').length > 0) {
                        $(this).addClass('has-error');
                    }
                });
            }
        });
    
        $('form').each(function () {
            $(this).find('div.form-group').each(function () {
                if ($(this).find('span.field-validation-error').length > 0) {
                    $(this).addClass('has-error');
                }
            });
        });
    });
    

    This is a combination of @german's answer and help from this post by "theBraindonor". Updated to use new Bootstrap 3 classes.

提交回复
热议问题