JQuery val () returning empty

I got stuck on what seems like a trivial issue, and I'm probably going to kick myself for missing it. In any case, my problem is that I am not getting the value from the text box.

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 was loaded.

The warning displays a blank dialog box.

If I included $(document).ready();in my script, the function is generateQuerynot called. Any idea why ..?

<script type="text/javascript">

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

        function generateQuery(){

            alert(username);

        }
    });     
</script>
+5
source share
5 answers

Assign your variable inside the function.

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

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

- . generateQuery document.ready, button onclick="generateQuery()".

+10

. , , . .

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

document.ready, . , .

+3

The value is displayed for the first time. Therefore, when the page is first loaded.

<script type="text/javascript">
        function generateQuery(){
            var username = $("#usernameText").val();
            alert(username);

        }
</script>
+1
source

Here you define the function that you must call the function in order to run it, using this line generateQuery();to call your function.

0
source

where do you call the function ????

I think you need:

<script type="text/javascript">

    $(document).ready(function(){
      generateQuery();


    });     

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

        }
</script>
-1
source

All Articles