I would like to create a system in which the number of elements increases when I press the input element below.
However, I would like the name of the newly generated element to be unique such as text_title1 and text_html1.
How will it work?
Please let me know if you know more.Thank you for your cooperation.
<li><input type="text" placeholder="Title" name="text_title" style="width:400px;height:20px;margin-bottom:10px;">/li>
<li><textarea placeholder="Contents" name="text_html" style="width:400px;height:300px;">/textarea></li>;;
There is jQuery in the tag, so here's an example: .append()
to add li
to the parent element ul
.
var number=1;
$(function(){
$("#button").click(function(){
$("#ul").append('<li><input name="text_title'+String(number)+'" type="text" placeholder="Title" style="width:400px;height:20px;margin-bottom:10px;"></li>);"
$("#ul").append('<li>textarea name="text_html'+String(number)+'"placeholder="Contents" style="width:400px;height:300px;">/textarea></li>');
number++;
});
});
I wrote it in JavaScript and html.
Press button to add elements and name is unique.
var button= document.getElementById("button");
var number = 1; // Number for unique name
var list = document.getElementById("list"); //li Get ul element to add element
button.onclick = function() {// button will call this function
var li = document.createElement("li");//<input type="text">Generate li element with
var li2=document.createElement("li");//<input type="textarea">Generate li element with
var input_text = document.createElement("input"); // Generate input
var input_textarea= document.createElement("input");
/********** US>*************/
input_text.type="text";
input_text.placeholder="Title";
input_text.name = "text_title" + String(number); // add number to make name unique
input_text.style.width="400px";
input_text.style.height="20px";
input_text.style.marginBottom="10px";
input_textarea.type="textarea";
input_textarea.placeholder="Contents";
input_textarea.name = "text_html" + String(number); // Add number to make name unique
input_textarea.style.width="400px";
input_textarea.style.height="300px";
/********** US>*********/
li.appendChild(input_text); // Add input_text to li
li2.appendChild(input_textarea);
list.appendChild(li); // Add li to body
list.appendChild(li2);
number++; // Add 1 to number
}
<!DOCTYPE html>
<html lang="ja">
<head>
<metacharset="utf-8">
<title>add Input Element</title>
</head>
<body>
<button id="button">Add Elements</button>
<ulid="list">
</ul>
</body>
</html>
© 2024 OneMinuteCode. All rights reserved.