Adding input elements dynamically to form
You could use an onclick
event handler in order to get the input value for the text field. Make sure you give the field an unique id
attribute so you can refer to it safely through document.getElementById()
:
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">
. Create new elements by means of document.createElement()
, and use appendChild()
to append each of them to the container. You might be interested in outputting a meaningful name
attribute (e.g. name="member"+i
for each of the dynamically generated <input>
s if they are to be submitted in a form.
Notice you could also create <br/>
elements with document.createElement('br')
. If you want to just output some text, you can use document.createTextNode()
instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes()
and removeChild()
together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
<div id="container"/>
</body>
</html>
Add input elements dynamically [pure JS]
You want to create a div and use appendChild to add a file and an input field :
window.addEventListener("load", function() { document.getElementById("add").addEventListener("click", function() { // Create a div var div = document.createElement("div");
// Create a file input var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("name", "file"); // You may want to change this
// Create a text input var text = document.createElement("input"); text.setAttribute("type", "text"); text.setAttribute("name", "text"); // you may want to change this
// add the file and text to the div div.appendChild(file); div.appendChild(text);
//Append the div to the container div document.getElementById("container").appendChild(div); });});
* { margin: 0; padding: 0; font-family: Arial;}
body { background-color: grey;}
h1 { color: white;}
h2 { color: darkgrey;}
<h1>Add input elements dynamically</h1><form> <div> <input type="button" value="add" id="add" /> <div id="container"> </div> </div></form>
Dynamically adding HTML form fields based on a number specified by the user
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
How to implement dynamic html form in order to add input elements horizontally and vertically with connected lines
About the lines:
under what I wrote before add a div
<div style="width:1000px;border-top:solid 1px gray;position:absoulte;top:-40px;"></div>
add lines as needed. top:40px is only an example, fit the right px you need.
If it does not work get back to me.
Add multiple input field dynamically in react
I would approach this from a configuration angle as it's a little more scalable. If you want to eventually change across to something like Formik or React Form, it makes the move a little easier.
Have an array of objects that you want to turn into input fields. Your main component should maintain state whether the <Form />
component is showing, and if it's visible pass in the config and any relevant handlers.
Your form component should maintain state for the inputs, and when you submit it, passes up the completed state to the parent.
const { Component } = React;
class Example extends Component {
constructor(props) {
super();
// The only state in the main component
// is whether the form is visible or not
this.state = { visible: false };
}
addForm = () => {
this.setState({ visible: true });
}
removeForm = () => {
this.setState({ visible: false });
}
handleSubmit = (form) => {
console.log(form);
}
render() {
const { visible } = this.state;
const { config } = this.props;
return (
<div>
<button
type="button"
onClick={this.addForm}
>Add form
</button>
{visible && (
<Form
config={config}
handleSubmit={this.handleSubmit}
handleClose={this.removeForm}
/>
)}
</div>
);
}
};
class Form extends Component {
constructor(props) {
super();
this.state = props.config.reduce((acc, c) => {
return { ...acc, [c.name]: '' };
}, {});
}
handleChange = (e) => {
const { name, value } = e.target;
this.setState({ [name]: value });
}
handleSubmit = () => {
this.props.handleSubmit(this.state);
}
render() {
const { name, email, phone } = this.state;
const { handleClose, config } = this.props;
return (
<div onChange={this.handleChange}>
{config.map(input => {
const { id, name, type, required } = input;
return (
<div>
<label>{name}</label>
<input key={id} name={name} type={type} required={required} />
</div>
)
})}
<button type="button" onClick={this.handleSubmit}>Submit form</button>
<button type="button" onClick={handleClose}>Remove form</button>
</div>
);
}
}
const config = [
{ id: 1, name: 'name', type: 'text', required: true },
{ id: 2, name: 'email', type: 'email', required: true },
{ id: 3, name: 'phone', type: 'phone', required: true }
];
ReactDOM.render(
<Example config={config} />,
document.getElementById('react')
);
input { display: block; }
label { text-transform: capitalize; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Related Topics
Load More Posts Ajax Button in Wordpress
Can Scripts Be Inserted With Innerhtml
Stop Form Refreshing Page on Submit
How to Know Which Radio Button Is Selected Via Jquery
Show/Hide 'Div' Using JavaScript
Load and Execution Sequence of a Web Page
Page Content Is Loaded With JavaScript and Jsoup Doesn't See It
Change Link Color of the Current Page With Css
Case Insensitive Xpath Contains() Possible
Make a Link Use Post Instead of Get
JavaScript - Append HTML to Container Element Without Innerhtml
How to Set Value of Input Text Using Jquery
How to Prevent a Click on a '#' Link from Jumping to Top of Page
Edit, Save, Self-Modifying HTML Document; Format Generated Html, JavaScript