我在使用输入类型文件时遇到问题
代码如下,
默认输入文件:
<div id="div_attachment">
<input name="f_attachment[]" type="file" class="file" id="f_attachment">
<input type="button" id="tb_more_files" value="more file"/>
</div>
和 jquery 代码:
$("input#tb_more_files").click(function(){
var new_file = $("<div><input id='f_attachment' name='f_attachment[]' type='file' class='file'/><input type='button' id='tb_remove' class='remove_file'></div>");
$("div#div_attachment").append(new_file);
});
我用这个验证附件文件的扩展名:
f_attachment = $("input#f_attachment").val();
FileType = f_attachment.split('.').pop().toLowerCase();
if(f_attachment == null || f_attachment == ""){
alert("Attachment is Empty");
}else if($.inArray(FileType, ['gif','png','jpg','jpeg']) == -1){
alert("Invalid Type of File Attachment");
}
问题是,当我点击更多文件按钮时 并出现输入文件元素, 当它有空值或空值或不同的文件类型验证时,我无法验证它!
我尝试使用 .live() 方法,但我不知道如何...
请帮忙!
最佳答案
$('#div_attachment').on("change",".file", function(event) {
value = $(this).val(); // the value of the file element
// do validation
});
这会监听元素 div_attachment
(您的父 div)中具有类 file
的所有元素的 change
事件并处理您的验证.使用 on()
意味着即使是新创建的 DOM 元素也会应用事件处理程序
您需要注意的一件事是对多个元素使用相同的 ID - 您最好使用一个类。
更新
要执行检查 onsubmit()
使用 each()
方法:
$('.file').each(function(index) {
value = $(this).val();
// some validation for $(this) using value
});
注意:使用 $('.file')
选择器获取类为 file
的所有元素
关于javascript - 验证新创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8725366/