Reputation: 737
I am trying to grab the value from my text input, and just alert it off of the button click for now. For whatever reason the alert is always blank? I've tried many different ways of going about this, but none of them have worked. Please help me SO. :\
As you can see here.
My HTML:
<input type="text" id="item_text" />
<button id="button1">ClickMe</button>
My jQuery:
$(document).ready(function(){
value = $("#item_text").attr('value');
$("#button1").click(function(){
alert(value);
});
});
Upvotes: 1
Views: 2356
Reputation: 5093
You have the value set on page load, then print it out on click. So if you changed
<input type="text" id="item_text" />
...to...
<input type="text" id="item_text" value="waffles"/>
...then the output will always be waffles. What you want to do is check the value on click, and then print it out.
The simplest way to fix this, would be to just check the value inside the click function like so:
$(document).ready(function(){
$("#button1").click(function(){
value = $("#item_text").attr('value');
alert(value);
});
});
As others have pointed out, it's better to use .val()
instead of .attr('value')
. Either way will work though
Upvotes: 4
Reputation: 3747
How about getting the value inside click event
$(document).ready(function(){
$("#button1").click(function(){
value = $("#item_text").val();
alert(value);
});
});
Upvotes: 2