简体   繁体   English

验证新创建的元素

[英]Validating newly created elements

i have problem when i use input type file 使用输入类型文件时出现问题

the code is like this below, 代码如下所示,

default input file : 默认输入文件:

<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>

and jquery code : 和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);
});

and i validate extension of attachment file with this : 我用这个来验证附件文件的扩展名:

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");
   }

and the problem is, when i clicked more file button and input file element is appear, i cannot validate it when it have empty or null value or different file type validation! 问题是,当我单击更多文件按钮并出现输入文件元素时,当它具有空值或null值或不同的文件类型验证时,我无法对其进行验证!

i try with .live() method, but i dont know how... 我尝试使用.live()方法,但是我不知道如何...

please help! 请帮忙!

$('#div_attachment').on("change",".file", function(event) {
  value = $(this).val(); // the value of the file element
  // do validation
});

this listens to the change event on all elements with the class file within the element div_attachment (your parent div) and processes your validation. 这将监听元素div_attachment (您的父div)中包含类file所有元素的change事件,并处理您的验证。 Using on() means that even newly created DOM elements will have the event handler applied 使用on()意味着即使新创建的DOM元素也将应用事件处理程序

One thing you need to be careful of is using the same ID for multiple elements - you are better using a class. 您需要注意的一件事是对多个元素使用相同的ID-最好使用一个类。

Update 更新资料

To perform the check onsubmit() use the each() method : 要执行onsubmit()检查,请使用each()方法:

$('.file').each(function(index) {
    value = $(this).val();
    // some validation for $(this) using value
});

NOTE: Using the $('.file') selector gets all the elements with the class file 注意:使用$('.file')选择器获取类file所有元素

Docs for each() , Docs for on() Docs for each()Docs for on()

Created a complete fiddle for you; 为您创建了完整的提琴; http://jsfiddle.net/7KLA6/ http://jsfiddle.net/7KLA6/

UPDATE Adding the code on request 更新根据要求添加代码

HTML 的HTML

<form name="myForm" enctype="multipart/form-data" method="post" action="">

<div id="div_attachment">
   <input name="f_attachment[]" type="file" class="file" id="f_attachment">
   <input type="button" id="tb_more_files" value="Add extra file" />
</div>

<input type="submit" id="submit_button" value="Submit form" />

</form>

JavaScript 的JavaScript

// Add file input
$("input#tb_more_files").click(function() {

    var new_file = $("<div><input name='f_attachment[]' type='file' class='file'/><input type='button' class='remove_file' value='Remove' /></div>");
    $("div#div_attachment").append(new_file);

});

// Remove added file input
$('#div_attachment').on('click', 'input.remove_file', function() {

    $(this).parent().remove();

});

// Validate on submit
$('form').submit(function() {

    var $form = $(this);
    var validForm = true;

    $form.find('input.file').each(function() {

        var $this = $(this);
        var fileName = $this.val();
        var fileType = fileName.split('.').pop().toLowerCase();

        if (fileName == null || fileName == "") {
            console.log("Attachment is Empty"); // DEBUG
            validForm = false;
        } else if ($.inArray(fileType, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
            console.log("Invalid Type of File Attachment"); // DEBUG
            validForm = false;
        }

        if (!validForm) {
            $this.css('color', 'red').focus();
            // Notice that only the last input will get the focus.
        }
    });

    console.log('Valid form =', validForm); // DEBUG
    return validForm;
});
<form name="myForm" enctype="multipart/form-data" action="" onsubmit="return  validateForm()" method="post">
        <input type="file" id="browse" name="browse" size="" placeholder="Photo" class="upload"/>


<input type="submit" name="submit" value="Submit"/>
</form>

<script>
function validateForm() {
    var x = document.forms["myForm"]["browse"].value;
    if (x == null || x == "") {
      //do somthing
        return false;
    } else {
      //do somthing
    }
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM