Prevent focusout/blur event in page load

899 Views Asked by At

I'm working on an MVC form and need to show the validation messages for the fields, when user moves to a next field.

But the validations are showing up on page load too. I tried focusout & blur.

HTML:

<input type="text" class="required" id="txtName"/>
<span class="validation" style="display:none;">This field is required</span> 

JS:

$(document).ready(function(){
    $(".validation").hide(); //this doesn't seem to work

    $(".required").blur(function () {        
        ValidateEmptyString();
    });
});

function ValidateEmptyString(){
   alert(); //triggers on page load
   .....
   $(".validation").show(); 
}
2

There are 2 best solutions below

1
Jas On

Try this instead:
Use the e.preventDefault()

$(document).ready(function(e){
    $(".validation").hide(); //this doesn't seem to work
    e.preventDefault()

    $(".required").blur(function () {        
        ValidateEmptyString();
    });
});

function ValidateEmptyString(e){
    e.preventDefault()
    $(".validation").show(); 
}

0
sukesh On

On document.ready, do no write the blur event action. Instead only add that event.

$(document).ready(function () {
    SetBlurEventForElements();
});

function SetBlurEventForCoPdElements() {
    var elements = document.getElementsByClassName('required');

    for (var i = 0; i < elements.length; i++) {
        (function (index) {
            elements[index].addEventListener("blur", function () {
                ValidateEmptyString(this);                
            });
        })(i);
    }
}

function ValidateEmptyString(e){    
    $(".validation").show(); 
}