动态创建文件类型验证

时间:2015-01-21 10:57:02

标签: jquery html5 file-type

此代码包含用于在按钮单击时动态添加和删除输入类型文件的jQuery,我想在onChange事件按钮上添加验证它不起作用:

var $j = jQuery.noConflict();
$j(document).ready(function(){

    var counter = 1;

    $j("#addButton").click(function () {

    if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
    }   

    var newTextBoxDiv = $j(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);
 //<label>Textbox #'+ counter + ' : </label>'
    newTextBoxDiv.after().html('<input type="file" name="ImageFile'+counter+'" id="ImageFile'+counter+'" value="" accept="audio/*,video/*,image/*"  multiple="multiple" required/>');

    newTextBoxDiv.appendTo("#TextBoxesGroup");

    alert('<input type="file" name="ImageFile'+counter+'" id="ImageFile'+counter+'" value="" accept="audio/*,video/*,image/*"  multiple="multiple" required/>');
    counter++;
    alert($j("#ImageFile").val());
     });

     $j("#removeButton").click(function () {
    if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

    counter--;

        $j("#TextBoxDiv" + counter).remove();

     });
     $j("#upload_type").on('change',function (){
    alert(); });

 $j("#ImageFile"+counter-1).on('change', function (){
     alert($j("#ImageFile").val());
     var avatar = $j("#ImageFile").val();
     var extension = avatar.split('.').pop().toUpperCase();
     alert(avatar);
     if(avatar.length < 1) {
             avatarok = 0;

         }
         else if (extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){ 
             avatarok = 0;
             alert("invalid extension "+extension);
         }
         else {
             alert("valid");
             avatarok = 1;
         }
         if(avatarok == 1) {
             $('.formValidation').addClass("sending");
             $("#form").submit();
         }
         else {
             $('.formValidation').addClass("validationError");
         }
         return false;
     });
         $j("#getButtonValue").click(function () {

        var msg = '';
    for(i=1; i<counter; i++){
      msg += "\n Textbox #" + i + " : " + $j('#ImageFile' + i).val();
    }
          alert(msg);
     }) ;
  });

不会触发更改事件,但是当我手动添加输入类型文件时,会触发更改事件。为什么是这样?

<div id='TextBoxesGroup'>

</div></CENTER></td></tr>
<tr><td >
<input type='button' value='Add Button' id='addButton'></td><td>
<input type='button' value='Remove Button' id='removeButton'></td><td>
<input type='button' value='Get TextBox Value' id='getButtonValue'></td></tr></table>

这是Html标记。

0 个答案:

没有答案