Khalil Hamani
Khalil Hamani

Reputation: 91

jQuery script runs in console but not from the file

I have a problem with this code :

$(document).ready(function() {
    sweetAlert("a");// This is just a test, and it runs successfully by the way!!!
});

$("#login").keyup(check);

function check() {
    $(this).val($(this).val().replace(/\s/g,"_"));
}

The browser is loading the file, I checked it from the inspector, plus it runs the .ready script. But it's not working with .keyup. Then when I copy/paste the line

$("#login").keyup(check);

in the console it works successfully.

Here's the html form if needed :

<input type="text" name="login" id="login"/>

Thanks for your help.

Upvotes: 0

Views: 2312

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Just move the .keyup inside the document ready function:

$(document).ready(function() {
    sweetAlert("a");// This is just a test, and it runs successfully by the way!!!
    $("#login").keyup(check);
});

The reason is, whatever code you write inside $(document).ready(function() { will get executed only after loading of all DOM Elements. When you say it doesn't work, when $("#login").keyup(check); executes, the #login would not have loaded. The $(document).ready(function() { will have it executed for you once all the elements are loaded. Whatever executes in the Console, gets executed after the document is fully loaded.

Upvotes: 5

Related Questions