Search code examples
javascriptjqueryhtmlfile-uploadhtml-input

How to set uploaded file's name to an input type:text on javascript in html


I want to add a File Upload control to my html page like below.

<input class="form-control valid" id="rptScreenShot" type="text" style="float:left;" runat="server"
                               data-val="true" data-val-maxlength="The field Report Sample must be a string or array type with a maximum length of '600'." 
                               data-val-maxlength-max="600" value="" aria-invalid="false" />
<label class="btn btn-default btn-file">
    Browse <input class="form-control" id="upld_sample1" type="file" name="file_rptsample1" style="display: none;">
</label>

What I could not manage to do is to catch the selected file after a user browsed a file and set it to the value of rptScreenShot via javascript or jquery. Any help would be appreciated.


Solution

  • Something like below?

    $("#upld_sample1").on("change", function(e){
      console.log("Fileinfo:", e.target.files[0])
      $("#rptScreenShot").val(e.target.files[0].name)
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input class="form-control valid" id="rptScreenShot" type="text" style="float:left;" runat="server" data-val="true" data-val-maxlength="The field Report Sample must be a string or array type with a maximum length of '600'." data-val-maxlength-max="600"
      value="" aria-invalid="false" />
    <label class="btn btn-default btn-file">
        Browse <input class="form-control" id="upld_sample1" type="file" name="file_rptsample1" style="display: none;">
    </label>