JQuery Get the value of the text input field when a button is pressed by pressing the button?

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, click the button, it always warns the initial value of the input, which "enters your search".

How can i fix this?

+5
source share
3 answers

The problem you are facing is that all this block of code is executed in the DOM ready event.

var term = $('#term').val();is evaluated only once and saved "enter your search" in the term variable. That's why no matter what you change the value, the variable still retains the initial value when rendering the page.

Instead, you should do something more like the following:

JQuery

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

id .

+15

, . "term" click...

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

You need to get the value click, notdocument ready

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

All Articles