Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery each event

Tags:

jquery

I am trying to validate a login form. I am taking children of a div and iterating to all input elements. Everything working fine.But when focus moves on to password field and if i remove all values of username it doesn't give required error. My code

<div class="login-contents">
    <input type="text" name="name" class="form-control login-check" id="login-name" placeholder="Username">
    <input type="password" name="pass" class="form-control login-check" id="login-pass" placeholder="Password">
</div>

<div id="login-error" class="alert alert-danger"></div> 

And Jquery

$(document).ready(function(){
    $("#login-form").prop("disabled",true);
    $("#login-error").removeClass("alert alert-danger");
    var name_min_length = 2;
    var pass_min_length = 5 ;

$(".login-contents").children('input').each(function(){
    $(".login-check").keyup(function(){
        var name = $("#login-name").val();
        name = jQuery.trim(name).length;
        var name_length = length_check(name,name_min_length);
        console.log(name_length);

        var pass = $("#login-pass").val();
        pass = jQuery.trim(pass).length;
        var pass_length = length_check(pass,pass_min_length);
        console.log(pass_length);
    });
});


function length_check(value,number){
    if (value < number) {
        $("#login-error").addClass("alert alert-danger").html("Minimum length");
    }
    else{
        $("#login-error").removeClass("alert alert-danger").html("");
        return true ;
    }
}
});

Any suggestion where i am doing wrong

like image 679
Amir Hossain Avatar asked Jan 28 '26 01:01

Amir Hossain


1 Answers

Everything seems right you just need to change your logic like following with lesser code:

No need of .each loop in this case you can access this (current element where keyup fired) in your code by using class selector .login-check!

$(".login-check").keyup(function(){
        var name = $(this).val();
        var elemType = $(this).attr('name')
        name = jQuery.trim(name).length;
        var length = length_check(name, elemType == 'name' ? name_min_length : pass_min_length); // if element is name length will be 2 otherwise 5 for pass
        console.log(length);
    });

Demo

like image 69
Dhaval Marthak Avatar answered Jan 30 '26 18:01

Dhaval Marthak