March 30, 2012

find texbox value using javascript?

Question by pradip

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:

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!