RunzWitScissors RunzWitScissors - 3 months ago 21
Javascript Question

Why is my function not playing nice with .ready?

I built my script in javascript and then decided to convert it to jQuery to simplify future functionality. When I added the .ready around my script my function is no longer visible. From my understanding about how .ready works its contents should only fire after the DOM has been created. So I would expect to see the result of console.log(userInput) - I've taken out most of the code for example purposes. But when I run the program firebug shows "ReferenceError: getInput is not defined".

Here is my html:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="script/script.js"></script>
</head>
<body>
<form>
Input: <input type="text" name="userInput" id="userInput" autofocus><br>
<input type="button" value="Submit" name="Submit" onclick="getInput()">
</form>
</body>
</html>


Here is my script:

$(document).ready(function() {
function getInput() {
var userInput = $('#userInput').val();
console.log(userInput);
}
});


If I remove the .ready function everything works as expected but I'm not sure why there is a conflict. I read this post (What exactly does $(document).ready guarantee?) which mentions adding an onload function, which I attempted, but I still got the same error.

Why is .ready causing a conflict? I don't need it but it still doesn't make sense to me. Can someone explain what the issue is or point me to a post that explains it?

Answer

You've made the mistake of using inline event handlers with jQuery.

Inline event handlers require the function to be available in the global scope (window.functionName), while document.ready has it's own scope that is not global, hence the function defined inside document.ready is not available to the inline event handler.

What you should've done, was use more jQuery

<form id="myForm">
    Input: <input type="text" name="userInput" id="userInput" autofocus>
    <br />
    <input type="submit" value="Submit">
</form>

-

$(document).ready(function() {
    $('#myForm').on('submit', function(e) {
        e.preventDefault();

        var userInput = $('#userInput').val(); 
        console.log(userInput);
    });
});

Using an actual submit button, and the forms submit event seems more appropriate.

Comments