1

I have a variable callled "myLocation".

I would like to take the value from my text box and feed it into "lat1" which is inside the variable "myLocation".

I have tried using the jQuery $().attr('value') function but it does not seem to work.

Any suggestions?

Here is my code:

<input type="text" id="input1">

$(document).ready(function () {
    $('#input1').keypress(function(event) {
        if (event.which == 13) {
            element1 = $('#input1').attr('value');

            var myLocation = {
                lat1: 2, // I wold like to feed data here from the textbox
                         // I tried element1 = $('#input1').attr('value'); but it does
                            not seem to work
                lng2: -56
            };
        };
    });
});
talemyn
  • 7,822
  • 4
  • 31
  • 52
minx
  • 33
  • 1
  • 6
  • You can't just drop JavaScript code in there, you need to put it in a ` –  Jan 27 '17 at 20:50
  • http://stackoverflow.com/questions/4088467/get-the-value-in-an-input-text-box – Dan Weber Jan 27 '17 at 20:54
  • Possible duplicate of [Get the value in an input text box](http://stackoverflow.com/questions/4088467/get-the-value-in-an-input-text-box) – Dan Weber Jan 27 '17 at 20:54
  • Works great Chris G. Thank you! – minx Jan 27 '17 at 21:12

2 Answers2

1

It's $('#input1').val() or $(this).val() within your function.

$(document).ready(function () {
  $('#input1').keypress(function( event ) {
    if ( event.which == 13 ) {
      element1 = $(this).val();
      console.log("Element 1: ", element1);    
        
      var myLocation = {
        lat1: $(this).val(), 
        lng2: -56
      };
      
    };
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type = "text" id = "input1">
Dan Weber
  • 1,227
  • 1
  • 11
  • 22
0

Change

element1 = $('#input1').attr('value');

to

element1 = $(this).val();  // 'this' refers to the input element itself, benefit is that it wont refetch; val() will get the value

Read up: .attr() | jQuery API Documentation


Working code snippet:

$(document).ready(function() {
  
  $('#input1').keypress(function(event) {
    
    if (event.which == 13) {

      var element1 = $('#input1').val();  // make sure to initialize using "var" or else element1 will be a global variable!
      
      var myLocation = {
        lat1: element1,
        lng2: -56
      };
      
      console.log('myLocation', myLocation); // verify it in your log!
    };
    
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138