Cong HS
Cong HS

Reputation: 145

Cannot get value of textbox by jquery

javascript

<script>
    jQuery(function ($) {                                  
        var userName = jQuery("#userName").val();

        $('#btnsubmit').click(function () {
            alert(userName);

        });
    });
</script>

HTML

<div class="contact">
    <div class="contact-form">
        <h2>Check Out</h2>
        <div>
            <span><label>Name</label></span>
            <span><input name="userName" type="text" class="textbox" id="userName"></span>
        </div>
    </div>
    <div class="clear"></div>
</div>

I cannot get the value of the textbox. It is always empty when I click the button. Please help me to the value of the textbox to use with ajax.

Upvotes: 0

Views: 226

Answers (2)

Stan Shaw
Stan Shaw

Reputation: 3034

Try this:

<script>
    jQuery(function( $ ) {
        $('#btnsubmit').click(function () {
            alert($("#userName").val());
        });
    });
</script>

Upvotes: 0

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93631

You are getting the username once at page load time, before you register the click handler, and then never getting it again.

You need to get the value fresh inside of the click handler.

    jQuery(function ($) {                                  

        $('#btnsubmit').click(function () {
            var userName = $("#userName").val();
            alert(userName);

        });
    });

Note, you are scoping a local $, so please use it instead of jQuery inside the DOM ready handler :)

Upvotes: 3

Related Questions