1

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.

0

3 Answers 3

3

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(); 
});
Sign up to request clarification or add additional context in comments.

1 Comment

That's it! Thank you. I also found another solution and I will post it in first post.
0
<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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.