フォームに入力要素を動的に追加する


89

フィールドセットを動的に追加することに関する多くのブログや投稿を読みましたが、それらはすべて非常に複雑な答えを示しています。私が必要とするのはそれほど複雑ではありません。

私のHTMLコード:

<input type="text" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails">Fill Details</a>

したがって、ユーザーはinputフィールドに整数値(javascriptを使用して検証をチェックしています)を入力します。Fill Detailsリンクをクリックすると、対応する数の入力フィールドが表示され、入力できます。javascriptを使用してこれを実現したいと思います。

私はJavaScriptのプロではありません。inputリンクを介してユーザーがフィールドに入力した整数を取得し、対応する数の入力フィールドを表示するにはどうすればよいかを考えていました。

回答:


149

onclickテキストフィールドの入力値を取得するために、イベントハンドラーを使用できます。次の方法idで安全に参照できるように、フィールドに一意の属性を指定してくださいdocument.getElementById()

要素を動的に追加する場合は、要素を配置するコンテナが必要です。たとえば、<div id="container">document.createElement()を使用appendChild()して新しい要素を作成し、を使用して各要素をコンテナに追加します。意味のあるname属性を出力することに興味があるかもしれません(たとえば、フォームで送信する場合name="member"+iは、動的に生成されたのそれぞれについて<input>

を使用して<br/>要素を作成することもできますdocument.createElement('br')。テキストを出力するだけの場合は、document.createTextNode()代わりに使用できます。

また、コンテナにデータが入力されるたびにコンテナをクリアしたい場合はhasChildNodes()removeChild()一緒に使用できます。

<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            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>

このJSFiddleの作業サンプルを参照してください。


私はあなたのアドバイスに従いました。しかし、私は上をクリックすると、ブラウザのコンソールを示し、このエラー:Uncaught TypeError: Cannot call method 'appendChild' of undefined
XAN

答えはとても役に立ちました。そして、CSSクラスをフィールドに追加するにはどうすればよいですか
Pravinraj Venkatachalam 2017

3
@Pravinよろしくお願いします。特定の要素にクラスを追加するにどうすればよいですか?を参照してください。基本的に使うinput.className += ' someCSSClass';
シャビ・ロペス

1
フォームを送信すると、動的に生成された新しいフィールドは、元のHTMLの一部であった他のフィールドのように送信されません。それらは視覚的に表示され、私はそれらを検査できますが、提出しません。なぜそれが起こるのか考えはありますか?
circle1 2018

@ circle1動的に生成された要素に一意のname属性があることを確認してください 。name属性を持つフォーム要素のみが、フォームの送信時に値が渡されます。
シャビ・ロペス

29

このJQueryコードを試して、フォーム、フィールド、および削除/削除の動作を動的に含めます。

$(document).ready(function() {
    var max_fields = 10;
    var wrapper = $(".container1");
    var add_button = $(".add_form_field");

    var x = 1;
    $(add_button).click(function(e) {
        e.preventDefault();
        if (x < max_fields) {
            x++;
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
        } else {
            alert('You Reached the limits')
        }
    });

    $(wrapper).on("click", ".delete", function(e) {
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
    <button class="add_form_field">Add New Field &nbsp; 
      <span style="font-size:16px; font-weight:bold;">+ </span>
    </button>
    <div><input type="text" name="mytext[]"></div>
</div>

ここでデモを参照してください


何か間違ったことをしているのかもしれませんが、私の場合、このフォームのテキストフィールドでEnterキーを押すと、[新しいフィールドの追加]ボタンの機能が起動します。これはおそらく望ましくない動作です...
Maxi Mus

1
<button type="button" ...>そして問題は解決されます。
マキシムス
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.