How do I get and store the value of the data-id
attribute? The value inside of it changes on button click, so I need a method that gets the value as it changes. I've tried document.getelementbyid/name/value but I get the only get the value stored from the first button click. The method I'm using now $(this).data('id')
returns nothing. Thanks
mustache file:
<td>
<form id="Form" action="./downloaddoc" method="GET">
<input type="hidden" name="p" value="download"/>
<input type="hidden" name="fileid" data-id="{{file_id}}"/>
<input class="button download_button" type="submit" value="Download">
</form>
</td>
js:
$(document).on('click', '.download_button', download_doc);
function download_doc(event) {
event.preventDefault();
var id = $(this).data('id');
console.log(id);
window.location.href = window.location.href + '?p=download&id=' + fileid;
}
You're searching for data attribute in the download button and not in the input field where it is actually present.
Add a class/id to the input field so that you can find it.
When you click on the button find the closest form and then find the input field which contains file id and extract the file id from it.
<td>
<form id="Form" action="./downloaddoc" method="GET">
<input type="hidden" name="p" value="download"/>
<!-- Added a class to the input field -->
<input type="hidden" name="field" class="input-download-file" data-id="{{file_id}}"/>
<input class="button download_button" type="submit" value="Download">
</form>
</td>
Javascript:
$(document).on('click', '.download_button', download_doc);
function download_doc(event) {
event.preventDefault();
// Find the closest form
var form = $(this).closest('form');
// Find the input field which constains the download file id
var input = $(form).find(".input-download-file");
// Get the file id
var id = $(input).data('id');
console.log(id);
window.location.href = window.location.href + '?p=download&id=' + fileid;
}