jQuery trigger file input

后端 未结 21 1579
梦如初夏
梦如初夏 2020-11-22 08:49

Am trying to trigger an upload box (browse button) using jQuery.
The method I have tried now is:

$(\'#fileinput\').trigger(\'click\');   
相关标签:
21条回答
  • 2020-11-22 09:23

    Check out my fiddle.

    http://jsfiddle.net/mohany2712/vaw8k/

    .uploadFile {
      visibility: hidden;
    }
    
    #uploadIcon {
      cursor: pointer;
    }
    <body>
      <div class="uploadBox">
        <label for="uploadFile" id="uploadIcon">
          <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/34/Icon_-_upload_photo_2.svg/512px-Icon_-_upload_photo_2.svg.png"  width="20px" height="20px"/>
        </label>
        <input type="file" value="upload" id="uploadFile" class="uploadFile" />
      </div>
    </body>

    0 讨论(0)
  • 2020-11-22 09:26

    Correct code:

    <style>
        .upload input[type='file']{
            position: absolute;
            float: left;
            opacity: 0; /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
            -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* For IE5 - 7 */
            filter: alpha(opacity=0);
            width: 100px; height: 30px; z-index: 51
        }
        .upload input[type='button']{
            width: 100px;
            height: 30px;
            z-index: 50;
        }
        .upload input[type='submit']{
            display: none;
        }
        .upload{
            width: 100px; height: 30px
        }
    </style>
    <div class="upload">
        <input type='file' ID="flArquivo" onchange="upload();" />
        <input type="button" value="Selecionar" onchange="open();" />
        <input type='submit' ID="btnEnviarImagem"  />
    </div>
    
    <script type="text/javascript">
        function open() {
            $('#flArquivo').click();
        }
        function upload() {
            $('#btnEnviarImagem').click();
        }
    </script>
    
    0 讨论(0)
  • 2020-11-22 09:26

    i had problems with custom client side validation for <input type="file"/> while using a fake button to trigger it and @Guillaume Bodi's solution worked for me (also with opacity: 0; on chrome)

    $("#MyForm").on("click", "#fake-button", function () {
            $("#uploadInput").focus().trigger("click");
        });
    

    and css style for upload input

    #uploadInput {
    opacity: 0.0; 
    filter: alpha(opacity=0); /* IE lt 8 */
    -ms-filter: "alpha(opacity=0)"; /* IE 8 */
    -khtml-opacity: 0.0; /* Safari 1.x */
    -moz-opacity: 0.0;
    }
    
    0 讨论(0)
提交回复
热议问题