jQuery - on button click, emulate input[type=“file”].change only in parent element
-
20-06-2021 - |
Question
I am not sure if title says what correctly I am trying to do but I don't know how to name that problem.
I am trying to add some style to input[type="file"] element using css and jquery. Here is my code:
<div class="input-file">
<input type="file"><label>Select file...</label><button type="button">...</button>
</div>
where INPUT has display: none style so it's not visible.
Javascript:
$('.input-file > button').live('click',function() {
$('input[type="file"]').click(); });
It works good if only 1 element is on page but if there are for example 3, whenever I click on button 1, it will fire function 3 times. I would like it to respond only for it's parent element which is <div class="input-file">
How could I use .parent or .before or whatever function can work to achieve this?
EDIT:
@Chandu has a great solution.
Also, another alternative would be $(this).prev().prev().click(); if elements are static and always in the same position.
Thank you @Chandu.
Solution
Try this:
$('.input-file > button').live('click',function() {
$(this).closest('.input-file').find('input[type="file"]').click();
});
Update:
If you are using jquery >= 1.7 then use this version with on
:
$('.input-file').on('click', 'button',function() {
$(this).closest('.input-file').find('input[type="file"]').click();
});
OTHER TIPS
<script type="text/javascript">
$(function () {
$('#btn-upload').click(function (e) {
e.preventDefault();
$('#file').click();
});
});
</script>
<style type="text/css">
#file { display:none; }
</style>
<div>
<input type="file" id="file" name="file" />
<button type="button" id="btn-upload">Image</button>
</div>
You can olso use label tag for emulate click. label tag emulate click input of current form with id like for attribute. Examle:
<label for="file-input">
Click me!
<input type="file" id="file-input" style="display:none;" />
</label>