Govind
Govind

Reputation: 979

Jquery blur is not retaining highlighted textbox color

I have below password control in my MVC3 view page and calling onblur function from the control itself,

@Html.PasswordFor(m => m.CurrentPass, new Dictionary<string, object> { { "id", "txtCurrentPass" }, { "name", "CurrentPass" }, { "Class", "textBoxPlacHold fieldLblMargin" }, { "onblur", "$(this).currPasswordBlur();" } })

below is the jquery function which i am calling,

$.fn.currPasswordBlur = function () {        
        if ($('[id="txtCurrentPass"]').val() == '') {
            $('#PasswordChangeErr').html("Please enter current password.");
            $('[id="txtCurrentPass"]').addClass('outLineRed');            
            $('#PasswordChangeErr').show();            
            $('#MsgSucc').attr("style", "background-color:White;");           
            $("html, body").animate({ scrollTop: 0 }, "slow");            
            return false;            
        }
        else {            
            $('#PasswordChangeErr').hide();            
            $('[id="txtCurrentPass"]').removeClass('outLineRed');
            $('#MsgSucc').attr("style", "background-color:#dfe5e6;");
        }

the below is highlighting the textbox in red color and when the execution reaches return false statement, the highlighted textbox is getting vanished.

$('[id="txtCurrentPass"]').addClass('outLineRed');

i need to retain the highlighted textbox even if i comeout of the textbox.

Upvotes: 1

Views: 132

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

Firstly, you can provide an anonymous object to the htmlAttributes parameter in the PasswordFor declaration, which will shorten it quite a lot. Also, you should use jQuery to bind your events, not clunky on* attributes:

@Html.PasswordFor(m => m.CurrentPass, new { "id" = "txtCurrentPass", "name" = "CurrentPass", @"class" = "textBoxPlacHold fieldLblMargin" })

Your current jQuery creates the function as a plugin, however it only relates to a single element, defined by id, so there is no point having a plugin. You can put your code in a single blur event handler:

$('#txtCurrentPass').blur(function() {
    var $el = $(this);
    if ($el.val() == '') {
        $('#PasswordChangeErr').html("Please enter current password.").show();
        $el.addClass('outLineRed');                
        $('#MsgSucc').css("background-color", "white");           
        $("html, body").animate({ scrollTop: 0 }, "slow");          
    }
    else {            
        $('#PasswordChangeErr').hide();            
        $el.removeClass('outLineRed');
        $('#MsgSucc').attr("style", "background-color:#dfe5e6;");
    }
});

Example fiddle

Note that when selecting by id you should use the # prefix on the id, as it is much quicker than the attribute selector.

Upvotes: 1

Related Questions