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" />
          <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>
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With