如何使用jQuery动态添加文本框?

时间:2017-04-07 11:39:07

标签: javascript jquery html

我在textbox点击no option时使用以下代码添加select box。这每次都会添加第一行。我需要为所选行添加textbox,但它没有正确添加。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <form id="form1" runat="server">
            <div>
                <input id="btnAdd" type="button" value="Add" />
                    <div id="TextBoxContainer">
                    <!--Textboxes will be added here -->
                </div>
              </div>
        </form>

        <script>
        $(function() {
            $("#btnAdd").bind("click", function() {
                AddControl();
            });

            $("#btnGet").bind("click", function() {
                var values = "";
                $("input[name=DynamicTextBox1]").each(function() {
                    values += $(this).val() + "\n";
                });
                  var values = "";
                $("input[name=DynamicTextBox2]").each(function() {
                    values += $(this).val() + "\n";
                });

                alert(values);
            });

            $("body").on("click", ".remove", function() {
                $(this).closest("div").remove();


                });
            });
        function GetDynamicTextBox1(value) {

                return '<input name = "DynamicTextBox1"  id="ingr_name" type="text" value = "' + value + '" required/>&nbsp'  +
                '<select name="selecval" onchange="selectres(this.value)" id="selecval"><option value="">Select</option><option value="1">Yes</option><option value="2">No</option></select>'
                +'<input name = "DynamicTextBox2" style="display:none" id="res_name" type="text" value = "' + value + '" required/>&nbsp'+ '<input type="button" value="Remove" class="remove" />'

                }
                function selectres(X){

                    var selection=X;
                    if(selection == '2'){
                        $("#res_name").show();
                    }else{
                        $("#res_name").hide();
                    }
                }
                function AddControl() {
                  var div = $("<div />");

                div.append(GetDynamicTextBox1(''));


                $("#TextBoxContainer").append(div);
            }


            </script>

请你从这个

中支持单个和双个quts
 function GetDynamicTextBox1(value) {

        return '<input name = "DynamicTextBox1"  id="ingr_name" type="text" value = "' + value + '" required/>&nbsp'  +
        '<select name="selecval" onchange="selectres(this.value)" id="selecval"><option value="">Select</option><option value="1">Yes</option><option value="2">No</option></select>'
        +$('body').append('<input name = "DynamicTextBox2" style="display:none" id="res_name" type="text" value = "' + value + '" required/>')&nbsp+ '<input type="button" value="Remove" class="remove" />'

        }   

2 个答案:

答案 0 :(得分:0)

我刚刚在onchange="selectres($(this))

下面更改了这个
function GetDynamicTextBox1(value) {

                return '<input name = "DynamicTextBox1"  id="ingr_name" type="text" value = "' + value + '" required/>&nbsp'  +
                '<select name="selecval" onchange="selectres($(this))" id="selecval"><option value="">Select</option><option value="1">Yes</option><option value="2">No</option></select>'
                +'<input name = "DynamicTextBox2" style="display:none" id="res_name" type="text" value = "' + value + '" required/>&nbsp'+ '<input type="button" value="Remove" class="remove" />'

                }

根据

更改了selectres()函数
function selectres(z){

                var selection=z.val();



                if(selection == '2'){
                    z.next('input').show();  
                }else{
                    z.next('input').hide();  
                }
            }

$(function() {
            $("#btnAdd").bind("click", function() {
                AddControl();
            });

            $("#btnGet").bind("click", function() {
                var values = "";
                $("input[name=DynamicTextBox1]").each(function() {
                    values += $(this).val() + "\n";
                });
                  var values = "";
                $("input[name=DynamicTextBox2]").each(function() {
                    values += $(this).val() + "\n";
                });

                alert(values);
            });

            $("body").on("click", ".remove", function() {
                $(this).closest("div").remove();


                });
            });
        function GetDynamicTextBox1(value) {

                return '<input name = "DynamicTextBox1"  id="ingr_name" type="text" value = "' + value + '" required/>&nbsp'  +
                '<select name="selecval" onchange="selectres($(this))" id="selecval"><option value="">Select</option><option value="1">Yes</option><option value="2">No</option></select>'
                +'<input name = "DynamicTextBox2" style="display:none" id="res_name" type="text" value = "' + value + '" required/>&nbsp'+ '<input type="button" value="Remove" class="remove" />'

                }
                function selectres(z){

                    var selection=z.val();

                    

                    if(selection == '2'){
                        z.next('input').show();  
                    }else{
                        z.next('input').hide();  
                    }
                }
                function AddControl() {
                  var div = $("<div />");

                div.append(GetDynamicTextBox1(''));


                $("#TextBoxContainer").append(div);
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <form id="form1" runat="server">
            <div>
                <input id="btnAdd" type="button" value="Add" />
                    <div id="TextBoxContainer">
                    <!--Textboxes will be added here -->
                </div>
              </div>
        </form>

答案 1 :(得分:0)

您的方法存在的问题是只有一个元素可以具有给定的id属性;如果多个元素共享相同的id(与#res_name元素的情况一样),则只会找到第一个元素。有很多方法可以使用$('[id=res_name]')选择器,但这是不合适的,因为它在DOM中留下了无效的HTML。

在这种情况下,我只是从正在添加的元素中删除了id属性,同时删除了内联事件处理程序,并使用以下事件委托替换了selectres()函数, jQuery的on()方法:

// binding the event-handler to the ancestor <form> element,
// assigning the anonymous function as the event-handler for
// the 'change' event when originating on elements matching
// the CSS 'select' selector:
$('form').on('change', 'select', function(e) {

  // converting the e.target (the <select> DOM node
  // upon which the event was originally triggered)
  // into a jQuery Object:
  $(e.target)
    // finding the matching siblings of the <select>
    // element which match the supplied selector,
    // which returns <input> elements of type=text
    // and whose name attribute is 'DynamicTextBox2':
    .siblings('input[type=text][name=DynamicTextBox2]')
    // toggling (showing or hiding) that <input> element
    // depending on whether the switch (the supplied
    // evaluation/assessment) returns true/truthy
    // (which will show the element) or false/falsey
    // (which will hide the element):
    .toggle(e.target.value === '2');
});

$(function() {
  $("#btnAdd").bind("click", function() {
    AddControl();
  });

  $("#btnGet").bind("click", function() {
    var values = "";
    $("input[name=DynamicTextBox1]").each(function() {
      values += $(this).val() + "\n";
    });
    var values = "";
    $("input[name=DynamicTextBox2]").each(function() {
      values += $(this).val() + "\n";
    });

    alert(values);
  });

  $("body").on("click", ".remove", function() {
    $(this).closest("div").remove();
  });
});
$('form').on('change', 'select', function(e) {
  $(e.target).siblings('input[type=text][name=DynamicTextBox2]').toggle(e.target.value === '2');
});

function GetDynamicTextBox1(value) {

  return '<input name = "DynamicTextBox1"  id="ingr_name" type="text" value = "' + value + '" required/>&nbsp' +
    '<select name="selecval"><option value="">Select</option><option value="1">Yes</option><option value="2">No</option></select>' +
    '<input name = "DynamicTextBox2" style="display:none" type="text" value = "' + value + '" required/>&nbsp' + '<input type="button" value="Remove" class="remove" />'

}

function AddControl() {
  var div = $("<div />");
  div.append(GetDynamicTextBox1(''));

  $("#TextBoxContainer").append(div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
  <div>
    <input id="btnAdd" type="button" value="Add" />
    <div id="TextBoxContainer">
      <!--Textboxes will be added here -->
    </div>
  </div>
</form>

JS Fiddle demo