Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery. Get text input field's value on button clicking event?

Tags:

jquery

html:

<div id="search">
  <input id="term" type="text" value="enter your search" />
  <button id="hit" type="button" name="">Search</button>
</div>

jQuery:

$(document).ready(function() {
  var term = $('#term').val();
  $('#hit').click(function() {
    alert(term);
  });
});

The problem is that , no matter what I type in the input field, then hit the button, it always alert the original input value which is "enter your search".

How can I fix it?

like image 864
gilzero Avatar asked May 29 '12 00:05

gilzero


People also ask

How will you get text inside an input tag event?

Answer: Use the value Property You can simply use the value property of the DOM input element to get the value of text input field. The following example will display the entered text in the input field on button click using JavaScript.

How can get input tag value in jQuery?

jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element.


2 Answers

The problem you're having is that this whole block of code gets executed on the DOM ready event.

var term = $('#term').val(); is being evaluated only once and storing 'enter your search' in the term variable. This is why no matter what you change the value to, the variable still holds the initial value when the page was rendered.

Instead what you should do is something more like the following:

JQuery

$(document).ready(function() {
  $('#hit').click(function() {
    alert($('#term').val());
  });
});

In this bit of code, the value of the element with id term is evaluated when the click event listener fires.

like image 167
Aaron Avatar answered Oct 12 '22 05:10

Aaron


Because you created the variable just when the document is ready.. try to create the variable "term" inside the click function...

  $(document).ready(function() {
      $('#hit').click(function(event) {
          var term = $('#term').val();
          alert(term);
      });
  });​
like image 30
rjmcb Avatar answered Oct 12 '22 05:10

rjmcb