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

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.


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

You need to get the value on click, rather than document ready

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

Tags:

Jquery