Question: I have this Javascript/JQuery code:

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">

    name = $("#name").val();

    alert("Name: " + name);

</script>

```

And this HTML:

```
<form name="report" action="send.php" method="post">

    <input type="text" name="name" id="name" value="Senna" />
    <input type="submit" value="Send" />

</form>

```

When the page loads i get "Name: undefined" instead of "Name: Senna".

Can someone help me to get the expected result?

Answer: 
> 
> While JavaScript provides the load event for executing code when a
>  page is rendered, this event does not get triggered until all assets
>  such as images have been completely received. In most cases, the
>  script can be run as soon as the DOM hierarchy has been fully
>  constructed. The handler passed to .ready() is guaranteed to be
>  executed after the DOM is ready, so this is usually the best place to
>  attach all other event handlers and run other jQuery code.
> 
> 
> 

You need to indicate to execute the function once the page has been loaded. Currently you are only defining it and not decalring when to execute it.

```
$(document).ready(function(){
    name = $('#name').val();
    alert('Name: ' + name);
});

```

Or:

```
$(function(){
    name = $('#name').val();
    alert('Name: ' + name);
});

```
You need the `document.ready` callback.

Place your code inside a function like this - 

```
$(function(){
  // code goes here
});

```

You need to use this callback to know when jQuery *and* the entire DOM is loaded. Only then can you start to manipulate the Markup and CSS with your jQuery code.

---

The code above is really just shorthand for this - 

```
$(document).ready(function(){
  // code goes here
});

```

This uses the `.ready()` method - <http://api.jquery.com/ready/>  

An extract from the description of the `.ready()` function -

> 
> ... The handler passed to `.ready()` is guaranteed to be executed after
>  the DOM is ready, so this is usually **the best place to attach all
>  other event handlers and run other jQuery code.** ... 
> 
> 
> 

emphasis added