2012-11-26 62 views
0

所以,我想要做的是添加多個文本字段並上傳多個文件。用戶只能看到1個字段上傳,直到點擊它,並且正在瀏覽文件。文本字段也一樣。當用戶點擊或開始在文本字段中輸入時,下一個會出現。到目前爲止,我沒有完成目標的運氣。我剛剛開始使用JavaScript,因此我的代碼被嚴重破壞,甚至不值得發佈。當點擊前一個字段時動態添加字段到我的表單

這樣做有什麼不同的方法,你知道利弊嗎?

編輯:這是我嘗試做的很多方法之一。

<form name="form"> 
<label for="file">Filename:</label> 
<input type="file" name="file[0]" id="file[0]" onclick="addForm()" /> 
</form> 
<br /> 

<script type="text/javascript"> 

var part1 = '<label for="file">Filename:</label> <input type="file" name="file['; 
var part2 = ']" id="file['; 
var part3 =']" onclick="form()" /><br />' 

var counter = 0; 

function addForm() 
{ 

if (document.form.file[counter].click) 
{ 
     document.write(part1 + counter + part2 + counter + part3); 
     counter++; 

} 
} 
</script> 
+3

如果你不能打擾顯示你的代碼(我們甚至可以一起工作,和提高,斷碼),那麼我們爲什麼還要不厭其煩地嘗試幫幫我?另外,請不要在你的問題中使用不必要的褻瀆。 –

+0

羅傑那個大衛! =) –

+0

1)你的變量和函數都有相同的名字。該函數將替換該變量。 2)'document.write(var form)'是無效的javascript。它將是'document.write(form)',但是你會想要改變函數名或變量名,使它們不匹配。 3)'document.write'將傳遞的文本添加到文檔的末尾,所以它不會被添加到你的表單元素。使用'appendChild' 4)我相信你所有的標籤都會指向第一個文件輸入。你最好離開標籤的'for'屬性並在其中嵌入文件輸入。 – Shmiddty

回答

1

這裏有一個快速的解決方案:http://jsfiddle.net/JTDZR/

這將增加一個新的文件輸入當選擇當前活動的文件輸入一個文件,那麼它會關閉當前文件輸入,所以只能一次一個啓用。

HTML

<form id="fups" name="form"> 
<label> 
    Filename: <input type="file" name="file[]" /> 
</label> 
</form>​ 

JS

var fups = document.getElementById("fups"); 
var file = document.form['file[]']; 

fups.onchange = function(){ 
    file.disabled = true; 
    var inp = document.createElement("input"); 
    inp.type = "file"; 
    inp.name = "file[]"; 
    var lab = document.createElement("label"); 
    lab.innerHTML = "Filename: "; 
    lab.appendChild(inp); 

    fups.appendChild(lab); 
    file = inp; 
}; 
+0

正是我在找的東西!謝謝! –

0

說你有這樣的HTML:

<form id="myForm"> 
    <input type="text" /> 
    <input type="file" /> 
    <!-- the JS won't affect this element --> 
    <input type="submit" /> 
</form> 

一個你可以使用JavaScript的相當簡化的版本是這樣的:

var formElement = document.getElementById("myForm"); 
var children = e.getElementsByTagName("input"); 
var allowedTypes = new Array("text", "", "file"); 
// note the empty string - it stands for the default "text" type 
for(var i=0; i<children.length) { 
    var input = children[i]; 
    if(0 > allowedTypes.indexOf(input.attributes.getNamedItem("type").value)) { 
     input.onFocus = function() { 
     formElement.innerHTML += input.outerHTML; 
     input.onFocus = null; 
     } 
    } 
} 

這可以在一個更復雜的例子派生,就像爲新輸入添加容器一樣,所以它們不會總是出現在表單的末尾。另外,我會考慮與jQuery合作。當然,這是個人觀點,但它爲我節省了大量時間和編碼。

+0

非常感謝你=) –

+0

不客氣。如果它回答你的問題,你可以將它標記爲:) – Ash

相關問題