2012-02-07 27 views
0
var $imagefile = $('<input />') 
    .attr({ 
     type: 'file', 
     name: 'imageFile', 
     id: 'imageFile' 
    }); 

上面是我創建文件輸入的代碼。如何在文件輸入爲空時不顯示警報?

下面是一個檢查,如果文件格式是一個錶行正確的代碼:

function validation() { 

    var marks = parseInt($("#total-weight").text());  
    var _qid = ""; 
    var _msg = ""; 


    var allowedTypes = ["jpg", "jpeg", "gif", "png"]; 

    var path = $("#imageFile").val(); 
    var ext = path.substring(path.lastIndexOf('.') + 1).toLowerCase(); 

    var alertValidation = ""; 
    // Note, this is just so it's declared... 
    $("tr.optionAndAnswer").each(function() { 


     _qid = $("td.qid",this).text(); 
     _msg = "You have errors on Question Number: " + _qid + "\n"; 


     $("#imageFile",this).each(function() { 

      if ($.inArray(ext, allowedTypes) < 0) { 
       alertValidation += '\n\u2022 Unsupported file type'; 
      } 

      if (alertValidation != "") { 
       return false; //Stop the each loop 
      } 
     }); 

     if(alertValidation != ""){ 
      return false; 
     } 
    }); 


    if (alertValidation != "") { 
     alert(_msg + alertValidation); 
     return false; 
    } 

    return true; 
} 

現在這工作正常通過識別文件類型是正確和不正確。問題是,如果在所有表格行中用戶不選擇一個文件,那麼它提出的警告是不正確的。

我怎樣才能得到它,以便它也允許用戶不選擇文件的空白文件輸入?

回答

1

,在該例程

$("#imageFile",this).each(function() { 

     if ($.inArray(ext, allowedTypes) < 0) { 
      alertValidation += '\n\u2022 Unsupported file type'; 
     } 

     if (alertValidation != "") { 
      return false; //Stop the each loop 
     } 
    }); 

您應該檢查,看它是否有一個值,如果是的話,繼續處理。事情是這樣的:

$("#imageFile",this).each(function() { 
    if($(this).val().length) { 
     // continue on 
    } 
}); 

我們的意見後,你或許應該使用一類選擇,而不是一個id選擇。所以,你創建代碼也許應該是這樣的:

var $imagefile = $('<input />') 
.attr({ 
    type: 'file', 
    name: 'imageFile', 
    class: 'imageFile' 
}); 

而且你的日常應該是:

$(".imageFile",this).each(... 

這樣,你可以迭代在集合。

+0

嗨,只是一個小問題,如果我有兩個錶行都有一個文件輸入,如果我選擇第一行的位圖文件和第二行的PNG,它實際上不應該顯示警報顯示第一行的警報,因爲它是一個位圖,爲什麼它不顯示警報消息呢? – user1182476 2012-02-07 01:41:15

+0

我認爲它可能與你使用文件類型選擇器的'id'屬性有關。每頁只能有一個'id',如果你有多個id,後續的'id'會替換DOM中的前一個。所以在你的例子中,第二個文件類型輸入**具有**有效的文件類型 - 因此沒有警報。這有幫助嗎? – daniel0mullins 2012-02-07 02:03:04

+0

我已將#imageFile更改爲.imageFile,但仍然是同樣的問題。如果第一行是位圖,第二行是png,它會顯示錯誤,但是如果它是其他方式,它不顯示錯誤? – user1182476 2012-02-07 02:12:50