Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery val() returning empty

I'm stuck on what seems like a trivial issue and I'm probably gonna kick myself for missing this..Anyway, my issue is I'm failing to get the value from a text field.

HTML:

<form>
        <label for="">Enter Username:</label>
        <input id="usernameText" type="text" size="30" />
        &nbsp;&nbsp;<input type="button" value="Generate" onclick="generateQuery(); return     false;" />
</form>

Javascript:

<script type="text/javascript">

        var username = $("#usernameText").val();

        function generateQuery(){

            alert(username);

        }
</script>

I did the following if (jQuery) {.. and made sure JQuery is loaded.

In the alert it displays an empty dialog box.

If I included the $(document).ready(); into my script the function generateQuery does not get called. Any idea why..?

<script type="text/javascript">

    $(document).ready(function(){
        var username = $("#usernameText").val();

        function generateQuery(){

            alert(username);

        }
    });     
</script>
like image 885
kaizenCoder Avatar asked Mar 25 '13 03:03

kaizenCoder


1 Answers

Assign your variable within the function.

function generateQuery(){
  var username = $("#usernameText").val();
  alert(username);
}

As for your other question, "If I included the $(document).ready(); into my script the function generate does not get called. Any idea why..?"

This happens because of scope. You wrap generateQuery inside an anonymous function when you add a document.ready handler, and therefore it's not visible to your button onclick="generateQuery()" code.

like image 168
ahren Avatar answered Sep 22 '22 00:09

ahren