2

I have an input text field:

<input type="text" id="from_input" class="form-control" placeholder="FROM">

I want to get the value of text when it changes. Here is my jquery code:

<script>
  var fromValue;
  $(document).ready(function(){
    $("#from_input").change(function() {
      fromValue = $(this).val();
    });
    console.log(fromValue);
  });
</script>

I am getting fromValue variable as undefined. I need to get the text field value for further calculation in whole script. How can I achieve this?

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
Apoorv
  • 45
  • 6
  • `fromValue` will only have some value when `#from_input` is changed... You'll need to change your logic or maybe [trigger](https://api.jquery.com/trigger/) a change on `#from_input` before logging the variable – Calvin Nunes Feb 11 '20 at 19:23

3 Answers3

1

You are logging the fromValue variable before the change event has fired.

Your code needs to be updated to log the variable inside of the closure:

<script>
  var fromValue;
  $(document).ready(function(){
    $("#from_input").change(function() {
      fromValue = $(this).val();
      console.log(fromValue);
    });
  });
</script>

If you attempt to access fromValue outside of this inner function, it will be undefined. Only within the inner function (more precisely, after the inner function is called) will it have a value.

If you want to use the value, you'll need to pass it from inside the function, e.g.

$("#from_input").change(function() {
  do_something($(this).val());
});

where do_something is defined elsewhere in the code and performs the further calculation you're trying to do.

You should read up on closures as that's what you're dealing with here.

gcochard
  • 11,408
  • 1
  • 26
  • 41
0

You can use the event argument. The event contains the target element. And I noticed that you console.log is outside the callback function. Your code probably works already but you just don't see it.

<script>
  var fromValue;
  $(document).ready(function(){
    $("#from_input").change(function(event) {
      fromValue = event.target.value;
      console.log(fromValue);
    });
  });
</script>
Michelangelo
  • 5,888
  • 5
  • 31
  • 50
0

A example:

$(function() {
  $('#itext').keyup(function() {
    var text = $(this).val();
    $('#result').text('Your text: ' + text);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="itext">
<br><label id="result">Your text: </label>
Henrique
  • 48
  • 5