Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery beginner - function to initiate by time

I am a rookie in JS, have a problem understanding JQUERY semantics.

I have a function written for checking the content of a cell.

Problem: the function just starts when the cell loses focus, if I click Submit, the error shows first, then it will run the function.

I want the function to run even when I am inside the cell. How to do it?

Initiated by this:

$(".user_id").blur(function(){ validateUserId($('.user_id')); });

The function:

function validateUserId(reference) {
    if ( 5 == $(reference).val().length ) {
        $.get('index.php?user=' + $(reference).val(), function(data) {
            if ( "error" == data ) {
                $(reference).parent().parent().addClass('error');
                alert('error');
            } else {
                $(reference).parent().parent().removeClass('error');
                $(reference).addClass('valid');
                $(reference).parent().parent().addClass('success');
            }
        });
    } else {
        alert('short');
        $(reference).parent().parent().addClass('error');
    }
}
like image 929
user1393675 Avatar asked May 14 '12 12:05

user1393675


2 Answers

$(".user_id").on('keyup', function(){
   validateUserId($(this)); 
});
like image 137
adeneo Avatar answered Oct 13 '22 19:10

adeneo


i would use the keyup event. So everytime somebody types a key in your input cell, the function will be executed.

 $(".user_id").on("keyup", function(){ validateUserId($(this)); });

I changed the $(".user_id"), you take the value from ,to $(this). Since you want the value of the field you did the keyup event on. (And not an other field, if there would be 2 fields with the same .user_id class.)

like image 1
Anonymous Avatar answered Oct 13 '22 20:10

Anonymous