Home > Article > Web Front-end > Example of how to dynamically add Form form elements using JavaScript
This article mainly introduces the method of JavaScript to dynamically add Form form elements. It analyzes the usage of functions related to the operation of JavaScript form elements and related precautions based on examples. Friends who are interested in JavaScript can refer to this article!
I have written similar articles before (such as: dynamically adding form elements input, button, etc. implemented in javascript), but now it seems relatively elementary, and I want to create an advanced and simple
scenario : The background needs to upload game screenshots, and the number of screenshots is uncertain, so the method of dynamically adding input nodes is used to achieve this effect
The main functions used are:
document.getElementById();
objNode.parentNode;
objNode.cloneNode() ;
objNode.removeAtrribute();
objNode.innerHTML();
objNode .appendChild();
html:
<p class="well well-sm"> <p class="form-group"> <label class="form-label">游戏截图:</label> <input type="file" name="jietu[]" class="form-input"> <span class="form-tip" onclick="add_jietu()"><font color="#428bca">点击添加游戏截图</font></span> </p> <p class="form-group" id="add_jietu"> <label class="form-label">游戏截图:</label> <input type="file" name="jietu[]" class="form-input"> </p> </p>
javascript:
<script type="text/javascript"> function add_jietu() { var add_jietu = document.getElementById('add_jietu'); var nodeFather = add_jietu.parentNode; var node_clone = add_jietu.cloneNode(); content = add_jietu.innerHTML; node_clone.removeAttribute('id'); node_clone.innerHTML = content; nodeFather.appendChild(node_clone); } </script>
Note:
1. The 6th line of js uses the "clone node" function. There is no html in the cloned node, and the 9th line of code is needed to fill in the content.
2. Use Clone function, because the variable type generated by this method is "node type", it can be used as a parameter in the appendChild() function
3. The variables obtained by the nextSibling and lastChild attributes of the node are Text type (in chrome Seen in the debugging window)
Related recommendations:
javascript browser user agent detection script method detailed explanation
Detailed explanation of JavaScript self-executing functions and jQuery extension methods
The above is the detailed content of Example of how to dynamically add Form form elements using JavaScript. For more information, please follow other related articles on the PHP Chinese website!