0

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.

1
  • +1 for at least using the combination of the shortcut jQuery DOM ready with locally scoped $. I don't see many others using it :) Commented Oct 31, 2014 at 14:50

2 Answers 2

3

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank TrueBlueAussie,I did it
0

Try this:

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

4 Comments

Any particular reason you replaced the shortcut DOM ready handler with scoped $ with the older version? They had that part correct.
I'm pleading ignorance, since I was unaware of the 'newer' version. Do you have a link or quick explanation?
Edited my answer. Is that correct? What is the advantage, here?
Now the circle is complete :) It is shorter and avoid clashes with other plugins that use a global $.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.