This article here to say a JavaScript implementation of a very practical function, is the upload attachment, you can dynamically add and delete file selection box, and then upload.
Theoretically, it is easier to achieve, but the actual work is still encountered two difficulties, these difficulties are attributed to a cause, that is, browser compatibility. There are two functions to be used in the script: insertAdjacentHTML and RemoveChild, and the two functions are not working properly under Firefox. It took me almost a day to search the Internet for solutions that were found, and I breathed a sigh of relief.
The specific two functions are as follows:
<script type= "Text/javascript" >
//delete file selection box
function RemoveFile (id) {
var new_tr = Id.parentnode;
try {
//new_tr.removenode (true);
Just IE, not the consortium;
Other idea
var tmp = New_tr.parentnode;
In order to be able to use in IE and Firefox, it is necessary to replace with another method, the most upper layer of the parent node, and then remove.
Tmp.removechild (NEW_TR);
} catch (e) {}
}
//Add File selection box
function AddFile (id)
{
var str = ' <div><input type= ' file ' runat= "Server" name= "file" onkeydown= "This.blur ();" oncontextmenu= "return false"/><input type= "button" value= " Delete the "style=" height:22px, "onclick=" RemoveFile (This)/></div> ' inserthtml '
("BeforeEnd", document.getElementById (ID), str);
</script>
This reference on the page:
<div>
<input type= "button" value= "Add Attachment (Add)" onclick= "AddFile (' myfile ')" >
</div>
<div id= "myfile" >
</div>
Another function is referenced in the AddFile function: inserthtml, this function is mainly for insertadjacenthtml under Firefox invalid situation rewrite, specific can search insertadjacenthtml find.
PS: Clear the contents of the File box
<input type=file name=ttt>
<input type=button onclick= "Ttt.select (); Document.execcommand (' Delete '); Value= clear the contents of the File box >
Second case
File upload, delete effect chart:
Just start:
Click on the button "select More", you can add a lot of selection files:
Click the button "Delete" after:
Implementation code:
CODE FLAW:!!!! In the delete function, I chose to delete the first element node instead of the actual deletion of the current button, do not know how to improve, to correct.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.