I'm in the process of building a web scraper for a homework assignment involving Express, Mongoose, Cheerio/axios, and Handlebars. My "/" route grabs the Mongoose objects and handlebars loads them to the page in individual cards. A save button is generated with an attribute data-id={{_id}}'
in these cards. I'm trying to access the attribute with jQuery when it's pressed to save it to another collection but $(this) is returning undefined.
js
$(document).ready(function () {
$("#artDiv").on("click", ".save", (event) => {
event.preventDefault();
let id = $(this).attr("data-id");
console.log($(this).data("id"));
console.log(id);
})
});
html
<div id="artDiv" class="container">
{{#obj}}
{{#each .}}
{{#if headline}}
<div id="articleCard" class="card">
<h5 class="card-header">{{altHead}}</h5>
<div class="card-body">
<h5 class="card-title">{{headline}}</h5>
<p class="card-text">{{desc}}</p>
<a href="{{link}}" target="_blank" class="btn btn-primary">Visit</a>
<button data-id="{{_id}}" data-control="saveBtn" type="button" class="btn btn-success save">Save</button>
</div>
</div>
{{/if}}
{{/each}}
{{/obj}}
</div>
If you want to have your clicked element in $(this)
, you cannot use arrow functions. You have to use $("#artDiv").on("click", ".save", function (event) { ... });
.