1

I'm trying to display the value/name of an input file to an element. The code runs normal .. but the problem is when the user clicks and select a file . the file doesn't show up the moment the user selects the file but instead it shows when user clicks on the upload button again . so how will i make the value of the input field to show up the moment the user makes the choice .

$(document).ready(function () {
    $(".filename").each(function () {
        $('.upload').click(function () {
            $('#file_button').click();
            var file = $('#file_button').val();
            if (file !== null) {
                if ($('.filename').val() !== null) {
                    $($('.filename')).empty();
                }
                $('<span>' + file + '</span>').appendTo('.filename');
            }
        });
    });
});

my CSS :

#file_button {
   display: none;  
} 

// then down goes the css for upload button

HTML :

<button type="button" class="upload"> Upload a File </button>
<p class="filename"> </p>
<input type="file" id="file_button"/> 
4
  • Bind an onchange event to the input. Commented Oct 9, 2013 at 22:47
  • $('#file_button').click(); is doing nothing Commented Oct 9, 2013 at 22:47
  • How ..? sorry forgot to say i'm still new in jquery @Nilotpal Barpujari Commented Oct 9, 2013 at 22:51
  • if(file !== null){ if($('.filename').val() !== null){ Looks like you really want to be sure. Guess what value will never be null. ;) Commented Oct 9, 2013 at 22:52

2 Answers 2

1

Check this one...

Demo Fiddle

$(document).ready(function () {
    $(".filename").each(function () {
        $('.upload').click(function () {
            $('#file_button').click();

        });

        $("#file_button").change(function () {
            var file = $('#file_button').val();
            if (file !== null) {
                if ($('.filename').val() !== null) {
                    $($('.filename')).empty();
                }
                $('<span>' + file + '</span>').appendTo('.filename');
            }
        });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0
$("#file_button").on('change',function(){
    alert('Selected');
});

Then do want you intended by replacing the alert.

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.