Jquery beginner - function to start by time

I am new to JS, I have a problem with JQUERY semantics.

I have a function written to check the contents of a cell.

Problem: the function is launched only when the cell loses focus, if I click "Submit", an error first appears, then it launches the function.

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

Initiated as follows:

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

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');
    }
}
+5
source share
5 answers
$(".user_id").on('keyup', function(){
   validateUserId($(this)); 
});
+4
source

I would use the keyup event. Therefore, every time someone enters a key into your input cell, the function will be executed.

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

$( ". user_id" ), $ $(this). , keyup. ( , 2 .user_id.)

+1

0
$("input[submit]").click(function(e){
    e.preventDefault();
    var valid = validateUserId($('.user_id')); // maybe the function could return a boolean value too instead of just adding classes to the HTML part
    if (valid) {
        $("#your_form_id").submit(); // only if the input is valid, submit it
    }
});

sidenote : "", , , blur()

0

http://jsfiddle.net/pomeh/GwswM/. :

  • DOM ,
  • jQuery,
  • if ,
  • AJAX ,
  • AJAX,
  • jQuery deferred, ( AJAX)

, :)

0

All Articles