1

I have a page portion as below;

<input name="test1" type="text" id="test1" class="test1">
<button value="hi" id="but">hi</button>

I want to get data inside text field entered by user. I tried the following;

$(document).ready(function(){
var test2 = $('#test1').val();
        $('#but').click(function() {
        alert(test2);
});
});

When user clicks button hi, the page alerts the text inside text field. But the alert is coming blank (without text) even with text inside. When I reload the page, the text inside text field remains there and when I click the button again, script works well alerting the text inside. Again when I clear the text and I give another text, and when I click button, the alert is coming with previous text.

I am using jQuery.

Here is the fiddle.

I want to get alert with text inside the text area. How can I do this?

1
  • 2
    move the test2 assign code inside the click event Commented Mar 3, 2012 at 7:28

3 Answers 3

1

You can do this:

$('#but').click(function() {
    alert($('#test1').val());
});​

Or:

$('#but').click(function() {
    var val = $('#test1').val();
    alert(val);
});​

Working Example

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

Comments

1

Here is very simplest way

<input name="test1" type="text" id="test1" class="test1">
<button value="hi" id="but" onclick="buttonClicked()">hi</button>

<script>
function buttonClicked(){
  alert(jQuery("input#test1").val())
}
</script>

Enjoy

Comments

1

You are getting the value on page load, outside of the handler. You need to move it inside of the click handler, otherwise you will just get the value that was fetched when the page loaded:

$(document).ready(function(){
    $('#but').click(function() {
         var test2 = $('#test1').val();
         alert(test2);
    });
});

Comments

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.