2

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">
Matt Tester
  • 4,663
  • 4
  • 29
  • 32
the tao
  • 253
  • 2
  • 6
  • 13
  • 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. – the tao Mar 09 '14 at 21:21
  • If you want to see `co_id` in the console, you have to define it as a global, so **outside** `$(document).ready(...)` function. – xmikex83 Mar 09 '14 at 21:26

2 Answers2

6

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>
1

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.

Rouven Weßling
  • 611
  • 4
  • 16