0

I have many labels and 1 input file.

<label for="uploadFile" data-albumid="1">upload Here</label>
<label for="uploadFile" data-albumid="2">upload Here</label>
<label for="uploadFile" data-albumid="3">upload Here</label>
<input id="uploadFile" type="file" style="display:hidden">
$('#uploadFile').on('change', function(e) {
// how to get the albumid data here ?
});
yarek
  • 11,278
  • 30
  • 120
  • 219
  • Possible duplicate of [How to get the data-id attribute?](http://stackoverflow.com/questions/5309926/how-to-get-the-data-id-attribute) – Matt S May 16 '17 at 21:54

1 Answers1

0

Put a click handler on the labels, and have it associate the choice with the input element using .data().

var albumId;
$('label').click(function() {
  albumId = $(this).data("albumid");
  $('#' + this.htmlFor).data('albumid', albumId);
});

$('#uploadFile').on('change', function(e) {
  alert("Changing album " + $(this).data('albumid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="uploadFile" data-albumid="1">upload #1</label><br>
<label for="uploadFile" data-albumid="2">upload #2</label><br>
<label for="uploadFile" data-albumid="3">upload #3</label>
<input id="uploadFile" type="file" style="display: none;">
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • yes: but I was looking for a more elegant solution without creating a GLOBAL variable, using the 'e' event maybe ? – yarek May 17 '17 at 14:50
  • As far as I can tell, there's nothing about the original click event that opened the file selector in the change event that occurs when you select something. – Barmar May 17 '17 at 15:58
  • Note that the variable doesn't have to be global, you can wrap the whole thing in an IIFE to keep the variable local. – Barmar May 17 '17 at 16:00
  • OK, no more global variable, I use `.data()` to store the choice with the input element. – Barmar May 17 '17 at 20:22