Reputation: 138
hear is my HTML:
<div>
<input type='text' />
<input id='mybutton' type='button' value='button'/>
</div>
I want to find text box value when button is clicked:
Upvotes: 1
Views: 114
Reputation: 3558
its easy way to get its.
using $("input[type='text']").val()
$('#mybutton').click(function(){
alert($("input[type='text']").val());
});
you can also be get using prevAll selector to get textbox
Diffrent way
$('#mybutton').click(function(){
alert($(this).prevAll('input[type=text]:first').val());
});
Demo : http://jsfiddle.net/Kfnjn/1/
Upvotes: 1
Reputation: 206488
$('input#mybutton').on('click',function(){
var inputVal = $('input[type=text]').val();
alert(inputVal);
});
You can also use a slightly more appropriate way to get the value:
$('input[type=text]').prop('value');
Upvotes: 1
Reputation: 7405
Without using JQuery :
if your text box has an id as below
<input type='text' id="txt" />
You can use button action as below
<input id='mybutton' type='button' value='button' onclick="alert(document.getElementById('txt').value);"/>
Else you can use
<input id='mybutton' type='button' value='button' onclick="alert(this.parentNode.childNodes[0].value);"/>
Upvotes: 1
Reputation: 3330
$("#mybutton").click(function(){
var text = $('input[type=text]').val();
alert(text)
})
Remember:
Add a ID to input text, by this way is is more easy find the correct element in the page
Upvotes: 2
Reputation: 79031
You can select the textbox using input[type=text]
but I do not recommend doing so as this is more of a genaralised selector and cover other textboxes too if they are present.
Instead, Give an id to the textbox, like:
<input type='text' id="mytextbox" />
Using jQuery:
$("#mybutton").click(function(){
var text = $('#mytextbox').val();
console.log(text);
});
Using javascript
textbox = document.getElementById("mytextbox");
mybutton = document.getElementById("mybutton");
mybutton.onclick = function() {
console.log(textbox.value);
};
Upvotes: 1
Reputation: 2628
Use Following Code for getting Text value using Jquery
$('#mybutton').click(function()
{
alert($('input').val());
});
See the JsFiddle Link: http://jsfiddle.net/nEGTv/10/
Upvotes: 1
Reputation: 1785
if you have only one text box then try
alert($('input[type=text]').val());
jsfiddle is here
Upvotes: 1
Reputation: 175906
If it always precedes that button you could;
var e = $("#mybutton").prev();
x = e.val();
Upvotes: 1
Reputation: 2795
$("#mybutton").click(function(){
var text = $("input[type=text]").val()
});
Upvotes: 1