9

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?

5 Answers 5

23

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

4

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

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

Comments

1

I know this is a pretty old thread but still I thought I'll post an answer,

Change your jQuery from this:

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

To this:

$(document).ready(function() {
  $('#hit').click(function() {
    var term = $('#term').val();
    alert(term);
  });
});
<div id="search">
  <input id="term" type="text" value="enter your search" />
  <button id="hit" type="button" name="">Search</button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Just declare the variable term onclick not before it is clicked. Becoz otherwise it takes the value of the input before the button was clicked.

Comments

0

This worked for me after trouble For int

function getValue(){
    $("qty").value = parseInt($("qty").value);
}

For string

function getValue(){
    $("qty").value = $("qty").value;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.