Alfred
Alfred

Reputation: 21406

Get value inside a text field - JavaScript - jQuery

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?

Upvotes: 1

Views: 4253

Answers (3)

Jeff B
Jeff B

Reputation: 30099

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);
    });
});

Upvotes: 1

Shivomkara Chaturvedi
Shivomkara Chaturvedi

Reputation: 1697

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

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382746

You can do this:

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

Or:

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

Working Example

Upvotes: 1

Related Questions