[英]How to select closet element in jQuery and fire change event to file input?
[英]on change event for file input element
我有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>
我该怎么办?
OnChange
活动是一个不错的选择。 但是,如果用户选择相同的图像,则不会触发该事件,因为当前值与前一个值相同。
例如,图像宽度发生变化,应该上传到服务器。
要防止出现此问题,您可以使用以下代码:
$(document).ready(function(){
$("input[type=file]").click(function(){
$(this).val("");
});
$("input[type=file]").change(function(){
alert($(this).val());
});
});
使用元素的files
filelist而不是val()
$("input[type=file]").on('change',function(){
alert(this.files[0].name);
});
为文件输入提供唯一的类和不同的id
$("#tab-content").on('change',class,function()
{
var id=$(this).attr('id');
$("#"+id).trigger(your function);
//for name of file input $("#"+id).attr("name");
});
对于想直接在文件输入上使用onchange事件的人,请设置onchange="somefunction()
, 链接中的示例代码:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.