Search code examples
jsffile-uploadjsf-2tomahawk

How can I check if a file is selected using t:inputFileUpload before submitting/uploading


I wanted to know if it is possible to check if a file is already selected prior to a click on submit/upload button?

The problem I want to solve with this option is to hide the "submit/upload" button if no file has already selected? Using required="true" attribute is not an option for me because the user doesn't always have to provide a file.


Solution

  • This is possible by initially hiding the upload button by CSS and attaching some JS to the change event of the file field which displays the upload button if a file has been selected.

    <h:form id="form">
        <t:inputFileUpload id="file" value="#{bean.file}" required="true" 
            onchange="document.getElementById('form:upload').style.display = (!!value) ? 'block' : 'none'" />
        <h:commandButton id="upload" value="Upload" action="#{bean.upload}" style="display: none;" />
    </h:form>