0

I have labels with for="#input_id" tag as illustrated below. However, multiple labels trigger the same input field (with id) to attach a user selected file. I want to now which label triggered the input field.

<label id="label1" for="input1">Document1</label>
<label id="label2" for="input1">Document2</label>
<label id="label3" for="input1">Document3</label>
<label id="label4" for="input1">Document4</label>

<input type="file" id="input1" accept="application/pdf" />

$("#input1").change(function() {
//some js for checking file type and file size etc
//looking for some code to findout which label clicked to trigger file input 

});

When i click labels it triggers input field however i need to know which label clicked to save file path to suitable div by using data-fpath="some path".

I use jquery however any javascript solution is OK for me.

aliaktas
  • 165
  • 10

1 Answers1

0

Please check below working snippet :

$("label").on('click',function(){
  $("label").removeClass('clicked');
  $(this).addClass('clicked');
});
$("#input1").change(function() {
  //some js for checking file type and file size etc
  //looking for some code to findout which label clicked to trigger file input 
  if($(".clicked").length>0){
    alert('Label with id : '+$(".clicked").attr('id')+' clicked to trigger file uploader.');
  }else{
    alert("No label has been clicked trigger file uploader.");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="label1" for="input1">Document1</label>
<label id="label2" for="input1">Document2</label>
<label id="label3" for="input1">Document3</label>
<label id="label4" for="input1">Document4</label>

<input type="file" id="input1" accept="application/pdf" />
Rahul Patel
  • 5,248
  • 2
  • 14
  • 26
  • Hi Rahul, your answer is a working one. However still first we need to catch click event of label and then catch change event of input field. I asked if someone know how the label's for event pass its own parameters (if so) to click event of input field. Thanks for your kind answer – aliaktas Oct 27 '16 at 09:35
  • @aliaktas where exact you want which label has been clicked to trigger file uploader field? – Rahul Patel Oct 27 '16 at 09:37
  • Yes, below explanation might be more clear: When you click a label with a **for** tag, it automatically fires an event for target object. However, i ask if that label with for tag, passes its parameters (id, class, etc) to triggered object ( in that case it is an input field) – aliaktas Oct 27 '16 at 09:39