Reputation: 27
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
};
};
});
});
Upvotes: 1
Views: 154
Reputation: 15501
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">
Upvotes: 0
Reputation: 1237
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">
Upvotes: 1