on file事件的变更事件

时间:2013-11-27 13:53:33

标签: javascript jquery html upload

我有4个文件输入,我希望它们的值在更改时触发上传进程。 我的意思是当您选择图片并单击选择图像对话框上的打开时,将触发上传图片的脚本。我已经使用了onchange事件,但我认为这不是正确的事件:

JS:

$("input[type=file]").on('change',function(){
    alert(this.val());//I mean name of the file
});

HTML:

<div class="form-group col-md-11 col-md-offset-1">
    <input type="file" name="photos[]">
    <input type="file" name="photos[]">
    <input type="file" name="photos[]">
    <input type="file" name="photos[]">
</div>

我该怎么办?

4 个答案:

答案 0 :(得分:23)

OnChange事件是一个不错的选择。但是,如果用户选择相同的图像,则不会触发该事件,因为当前值与前一个值相同。

例如,图像宽度发生变化,应该上传到服务器。

要防止出现此问题,您可以使用以下代码:

$(document).ready(function(){
    $("input[type=file]").click(function(){
        $(this).val("");
    });

    $("input[type=file]").change(function(){
        alert($(this).val());
    });
});

答案 1 :(得分:10)

使用元素的files文件列表而不是val()

$("input[type=file]").on('change',function(){
    alert(this.files[0].name);
});

答案 2 :(得分:1)

为文件输入提供唯一的类和不同的ID

           $("#tab-content").on('change',class,function()
               {
                  var id=$(this).attr('id');
                      $("#"+id).trigger(your function); 
               //for name of file input  $("#"+id).attr("name");
               });

答案 3 :(得分:0)

对于想直接在文件输入中使用onchange事件的人,请设置onchange="somefunction(),例如the link中的示例代码:

<html>
<body>
    <script language="JavaScript">
    function inform(){
        document.form1.msg.value = "Filename has been changed";
    }
    </script>
    <form name="form1">
    Please choose a file.
    <input type="file" name="uploadbox" size="35" onChange='inform()'>
    <br><br>
    Message:
    <input type="text" name="msg" size="40">
    </form>
</body>
</html>
相关问题