pradip
pradip

Reputation: 138

find texbox value using javascript?

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

Answers (9)

Jignesh Rajput
Jignesh Rajput

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

Roko C. Buljan
Roko C. Buljan

Reputation: 206488

jsBin demo

$('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

prageeth
prageeth

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

Gadonski
Gadonski

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

Starx
Starx

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

Rony SP
Rony SP

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

Amritpal Singh
Amritpal Singh

Reputation: 1785

if you have only one text box then try

alert(​$('input[type=text]')​.val()​);​

jsfiddle is here

Upvotes: 1

Alex K.
Alex K.

Reputation: 175906

If it always precedes that button you could;

var e = $("#mybutton").prev();
x = e.val();

Upvotes: 1

Sunil Kumar B M
Sunil Kumar B M

Reputation: 2795

$("#mybutton").click(function(){
    var text = $("input[type=text]").val()
});

Upvotes: 1

Related Questions