1

以下のinput要素をボタンを押すと要素が増えるといった仕組みを作りたいと思っています。
ただ、新しく生成した要素のnameはtext_title1やtext_html1といったユニークなものにしたいです。
どのようにすればうまくいきますでしょうか。
詳しい方、ご教示下さい。宜しくお願い致します。

<li><input type="text" placeholder="タイトル" name="text_title" style="width:400px;height:20px;margin-bottom:10px;"></li>
<li><textarea placeholder="内容" name="text_html" style="width:400px;height:300px;"></textarea></li>

2 件の回答 2

1

タグにjQueryがあるので、その例です。.append()で親要素ulの中にliを追加します。

var number = 1;

$(function(){
    $("#button").click(function(){
        $("#ul").append('<li><input name="text_title' + String(number) + '" type="text" placeholder="タイトル" style="width:400px;height:20px;margin-bottom:10px;"></li>');
        $("#ul").append('<li><textarea name="text_html' + String(number) + '" placeholder="内容" style="width:400px;height:300px;"></textarea></li>');
        number++;
    });
});
0

JavaScriptとhtmlで書いてみました。
buttonを押すと要素が追加されていき、nameもユニークです。

var button = document.getElementById("button");
var number = 1; //ユニークなnameのための数字
var list = document.getElementById("list"); // li要素を追加するul要素を取得

button.onclick = function () { // buttonをクリックしたらこの関数が呼ばれる
    var li = document.createElement("li"); //<input type="text">を入れるli要素を生成
    var li2 = document.createElement("li"); //<input type="textarea">を入れるli要素を生成
    var input_text = document.createElement("input"); //inputの生成
    var input_textarea = document.createElement("input");

/********** inputのいろいろな属性の設定 ***********/        
    input_text.type = "text"; 
    input_text.placeholder = "タイトル";
    input_text.name = "text_title" + String(number); //numberを追加してnameをユニークにする
    input_text.style.width = "400px";
    input_text.style.height = "20px";
    input_text.style.marginBottom = "10px";

    input_textarea.type = "textarea";
    input_textarea.placeholder = "内容";
    input_textarea.name = "text_html" + String(number); //numberを追加してnameをユニークにする
    input_textarea.style.width = "400px";
    input_textarea.style.height = "300px";
  
/********** 属性の設定終わり **********/

    li.appendChild(input_text); //liにinput_textを追加
    li2.appendChild(input_textarea);

    list.appendChild(li); //bodyにliを追加
    list.appendChild(li2);
    
    number++; //numberに1を足す

}
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>add Input Element</title>
    </head>
    <body>
        <button id="button">要素を追加</button>
        <ul id="list">
        </ul>
    </body>
</html>

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。