Mashhoor Gulati
Mashhoor Gulati

Reputation: 127

no value of textbox captured on first attempt by jquery

I've this simple code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 

</head>
<body>
    <form id="form1" runat="server">
    <div>

        <script>
            $(document).ready(function () {

                var username = $("#txtusername").val();
                $("#btnsubmit").click(function () {
                    alert(username);
                });
            })
        </script>

    <asp:Label ID="lblusername" Text="User Name:" runat="server"></asp:Label>
        <asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
        <asp:Label ID="lblpass" Text="Password:" runat="server"></asp:Label>
        <asp:TextBox ID="txtpass" runat="server"></asp:TextBox>
        <asp:Button ID="btnsubmit" Text="Submit" runat="server" />
    </div>
    </form>
</body>
</html>

When I run this in browser, provide value to the textbox and click on button it alerts blank. when clicked next time shows the value. what could be the issue.?

1st Attempt. enter image description here

2nd Attempt.

enter image description here

Upvotes: 0

Views: 91

Answers (2)

prasanth
prasanth

Reputation: 22500

Try this.Define the variable inside the click function .Otherwise its get the initial value of the input box empty

$(document).ready(function() {
    var username = $("#txtusername").val();
    console.log('for initial input='+username) //initial value
  $("#btnsubmit").click(function() {
    var username = $("#txtusername").val();
     console.log('after click input='+username) //after
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtusername">
<button id="btnsubmit">click</button>

Upvotes: 1

Nisarg Shah
Nisarg Shah

Reputation: 14561

That's because you are reading the value outside the event handler. Essentially you want to read the value of the textbox when the user clicks on the submit button, not before it.

It could be written as follows:

$(document).ready(function() {
  // This code is executed when the page loads.
  $("#btnsubmit").click(function() {
    // This code is executed when the user clicks on the submit button.
    var username = $("#txtusername").val();
    alert(username);
  });
})

Upvotes: 1

Related Questions