I know questions similar to this wrt the confusing nature of $(this) have been asked many times before, but I still couldn't figure this out reading through them; apologies in advance if this is really simple / already answered elsewhere.
I have an input form with an autocomplete which gets its suggestions from a JSON file.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="style.css">
<title>HTML Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" name="example" id="example">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="code.js"></script>
</body>
Then I have some javascript
$(document).ready(function () {
$("#example").autocomplete({
source: function () {
console.log($(this).prop("id"));
var suggestions = [];
$.getJSON("parameters.json", function (data) {
$.each(data, function (key, val) {
if (key == $(this).prop("id")) {
suggestions = val;
}
});
})
return suggestions;
}
});
$("#example").keyup(function () {
console.log($(this).prop("id"));
})
});
The console.log($(this).prop("id"));
in the $("#example").keyup()
event handler binder outputs "example", as expected. However, the console.log($(this).prop("id"));
in the code for the autocomplete widget outputs Undefined
. Why is this happening? If I remove the .prop("id")
from both then they return
Where the top object is outputted from the keyup and the bottom is from the autocomplete.
Could anyone explain the discrepancy here? Thanks!