2016-05-13 21 views
-1

我有多個具有不同ID的輸入文件。我想統計文件的數量並獲取文件的名稱。 Javascript從文件輸入元素中獲取具有不同id的文件的數量而沒有多個屬性?

<div class="fieldContainer"><input type="file" class="txtField" name="fileAttach[]" id="filename1"></div> 
 
<div class="fieldContainer"><input type="file" class="txtField" name="fileAttach[]" id="filename2" ></div> 
 
<div class="fieldContainer"><input type="file" class="txtField" name="fileAttach[]" id="filename3" ></div>

+0

你有什麼要求? – Neoaptt

+0

我的回答有用嗎? – Mohammad

回答

2

您可以嘗試使用querySelectorAll API通過傳遞所需的選擇。 請找到的jsfiddle

var count = document.querySelectorAll(".fieldContainer > input[type='file']") 
alert(count.length); 

https://jsfiddle.net/smv3b53w/

+0

謝謝Jain。它有助於很多。 – Raj

0

如果我理解正確你的要求,你可以使用jQuery的一點點在這裏算每個文件並增加一個變量。

var i = 0; //variable to count each file - starting at 0 
$('input[type="file"]').each(function(){ 
    alert($(this).attr('id')); //alerts for each file found 
    i++; // adds 1 to the variable "i" 
}); 
alert("there are "+i+" files."); // alerts the final count of variable "i" - giving you the total number of files 

看到小提琴這裏:https://jsfiddle.net/mgtyxusm/1/

0

input選擇的文件,文件的對象添加名稱,然後寫在HTML對象的內容。

var files = {}; 
 
$("input").on("change", function(e){ 
 
    var count = 0; 
 
    var id = $(this).prop("id"); 
 
    files[id] = $(this)[0].files[0].name; 
 
    
 
    $("ol").html(""); 
 
    $.each(files, function(key, value){ 
 
     $("ol").append("<li>"+ value +"</li>"); 
 
     count++; 
 
    }); 
 
    $("#count").text(count + " Items selected"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <input type="file" id="filename1" /> 
 
<div> 
 
    <input type="file" id="filename2" /> 
 
</div> 
 
<div> 
 
    <input type="file" id="filename3" /> 
 
</div> 
 
<div id="count"></div> 
 
<ol></ol>

相關問題