console.log not working for jQuery?

15,174

Solution 1

Don't write code if you set the src attribute.

 <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
</script>
<script type="text/javascript">
$(document).ready(function () {
    $('#login').click(function() {
        var co_id = $('#companies').val();
        console.log(co_id);   
    });
});
</script>

Solution 2

Your problem is, that the Chrome console is always running in the global scope but co_id is scoped to the closure.

To inspect the values you have 3 options:

  1. Declare co_id to be in the global scope. To do this simply remove the var in front of the variable name and add var co_id in the global scope. I don't recommend this, inevitably you'll forget to make the scope local again and you'll end up with a lot of global variables. They can be a source of a lot of fun bugs.

  2. Change the console.log() to actually output the variable content like this: console.log(co_id);.

  3. The best solution: Set a break point in the function by clicking on the line number in the script pane.

Share:
15,174
the tao
Author by

the tao

Updated on November 26, 2022

Comments

  • the tao
    the tao over 1 year

    Here is my jQuery at the bottom of html page:

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
        $(document).ready(function () {
            $('#login').click(function() {
                var co_id = $('#companies').val();
                console.log(co_id); 
            });
        });
        </script>
    

    When I type this jQuery into the console, then type co_id it works, but when I run this in browser and choose a company and click the correct button, and I would assume when I type co_id into chrome browser console, it would show my option value? But it is coming back as:

    >co_id
    ReferenceError: co_id is not defined
    

    Here is html:

    <select name="" id="companies">
        <option value="--">--</option>
        <option value="1">Company</option>
        <option value="2">Company2</option>
        <option value="3">Company3</option>
        <option value="68">Company4</option>
        <option value="69">Company5</option>
        <option value="70">Company6</option>
    </select><input id="login" type="submit" value="Login">
    
    • the tao
      the tao about 10 years
      True, but shouldn't I still see 'co_id' come back as defined each time I type it? It is still declaring it as a string...I have actually already tried it with your method and it still comes back undefined.
    • xmikex83
      xmikex83 about 10 years
      If you want to see co_id in the console, you have to define it as a global, so outside $(document).ready(...) function.
  • the tao
    the tao about 10 years
    Lol, wish I could give you the answer. I have to wait 7 minutes. Thanks.