kaizenCoder
kaizenCoder

Reputation: 2229

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>

Upvotes: 6

Views: 11647

Answers (5)

keshu_vats
keshu_vats

Reputation: 442

Here you are defining the function you have to call the function in order to get it run use this generateQuery(); line to call your function.

Upvotes: 0

judda
judda

Reputation: 3972

The value is being derived the first time through. So when the page is first loaded.

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

        }
</script>

Upvotes: 1

ahren
ahren

Reputation: 16961

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.

Upvotes: 10

Sangeeta
Sangeeta

Reputation: 388

where are you calling the function????

i think you need:

<script type="text/javascript">

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


    });     

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

        }
</script>

Upvotes: -1

PSR
PSR

Reputation: 40318

Here it will call while the page is loading.So whenever the page is loading the text box is empty.Try to write within a function.

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

When you write in document.ready it will cal;l while the page is loading.If you need the value of username then call explicitly.

Upvotes: 3

Related Questions