使用javascript在按钮单击上添加文本框

时间:2016-03-22 11:26:47

标签: javascript html

以下代码将在单击事件上添加新文本框,但在单击“提交”按钮后,新添加的文本框不会保存。 请解决这个问题。

HTML

<table class="form-table">
    <tr valign="top">
        <td id="container_width">
            <input type="text" name="width" placeholder="" />
        </td>

        <td id="container_height">
            <input type="text" name="height"placeholder="" />
        </td>

        <td>
            <input type="button" name="increment" id="increment" value="+">
        </td>
    </tr>

    <tr>
        <td>
            <input type="submit" value="Save settings"/>
        </td>
    </tr>
</table>


//javascript

$('#increment').click(function(){
    var width = document.getElementById("container_width");
    var input;
    input = document.createElement("input");
    input.type = "text";
    input.name ="width[]";
    var br = document.createElement("br");
    width.appendChild(br);
    width.appendChild(input);

    var height = document.getElementById("container_height");
    var input;
    input = document.createElement("input");
    input.type = "text";
    input.name ="height[]";
    var br = document.createElement("br");
    height.appendChild(br);
    height.appendChild(input);
});

7 个答案:

答案 0 :(得分:3)

将[]添加到初始文本输入名称。这应该可以解决问题:

<input type="text" name="width[]" placeholder="" />

<input type="text" name="height[]" placeholder="" />

答案 1 :(得分:1)

请试试这个

$('#increment').click(function(){
 var html = "<input type="text" name = "newText" id = "textId">
$(this).append(html);
})

答案 2 :(得分:1)

您需要先在表单中包装输入。然后按照其他响应中的建议,将原始宽度和高度更改为width []和height []。此外,由于您已经在使用jQuery,因此您可以使用它来添加元素(尽管不是必需的)。

<form id="exampleForm">
<table class="form-table">



    <tr valign="top">
        <td id="container_width">
            <input type="text" name="width[]" placeholder="" />
        </td>

        <td id="container_height">
            <input type="text" name="height[]" placeholder="" />
        </td>

        <td>
            <input type="button" name="increment" id="increment" value="+">
        </td>
    </tr>

    <tr>
        <td>
            <input type="submit" value="Save settings"/>
        </td>
    </tr>

</table>
</form>

JSCode:

$(document).ready(function () {
  $('#increment').click(function(){
      var width = $("#container_width");
      var input;
      var input = $("<input>").attr("type","text").attr("name","width[]");
      var br = $("<br>");
      width.append(br);
      width.append(input);

      var height = $("#container_height");
      var input = $("<input>").attr("type","text").attr("name","height[]");
      var br = $("<br>");
      height.append(br);
      height.append(input);
  });
});

示例小提琴:

https://jsfiddle.net/1rh480kq/1/

答案 3 :(得分:1)

HTML:

<table class="form-table" id="customFields">
<tr valign="top">
    <th scope="row"><label for="customFieldName"></label></th>
    <td>
        <input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp;
        <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp;
        <a href="javascript:void(0);" class="addCF">Add</a>
    </td>
</tr>

JavaScript的:

$(document).ready(function(){
$(".addCF").click(function(){
    $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName"></label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click','.remCF',function(){
    $(this).parent().parent().remove();
});
});

尝试This JsFiddle,您可以动态添加和删除表格行。

答案 4 :(得分:1)

尝试使用它来调用服务器端方法

    var txtValList = [];
    txtValList.push($('txtVal1').val());
    txtValList.push($('txtVal2').val());
    txtValList.push($('txtVal3').val());
    $.ajax({
                method: "POST",
                url: "ServerSideMethod",
                data: JSON.stringify(txtValList),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    //On success
                },
                error:function()
                {
                    alert('some error occurred');
                }
            });

您也可以参考this link查看如何使用ajax和WebMethod

答案 5 :(得分:1)

$(document).ready(function () {
  $('#increment').click(function(){
   var width = $("#container_width");
   var input;
   var input = $("<input>").attr("type","text").attr("name","width[]");
   var br = $("<br>");
   width.append(br);
   width.append(input);

   var height = $("#container_height");
   var input = $("<input>").attr("type","text").attr("name","height[]");
   var br = $("<br>");
   height.append(br);
   height.append(input);
  });
});

答案 6 :(得分:0)

尝试一下

<html>
<head>
    <title>Create Elements Dynamically using jQuery</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
</head>

<body>
    <p>Click the button and each will perform some dynamic function!</p>
    <div id="main">
        <input type="button" id="btAdd" value="Add Element" class="bt" />
        <input type="button" id="btRemove" value="Remove Element" class="bt" />
        <input type="button" id="btRemoveAll" value="Remove All" class="bt" /><br />
    </div>
</body>
            
<script>
    $(document).ready(function() {

        var iCnt = 0;
        // CREATE A "DIV" ELEMENT AND DESIGN IT USING jQuery ".css()" CLASS.
        var container = $(document.createElement('div')).css({
            padding: '5px', margin: '20px', width: '170px', border: '1px dashed',
            borderTopColor: '#999', borderBottomColor: '#999',
            borderLeftColor: '#999', borderRightColor: '#999'
        });

        $('#btAdd').click(function() {
            if (iCnt <= 19) {

                iCnt = iCnt + 1;

                // ADD TEXTBOX.
                $(container).append('<input type=text class="input" id=tb' + iCnt + ' ' +
                    'value="Item ' + iCnt + '" />','<input type=date class="input" id=tb' + iCnt + ' ' + 'value="' + iCnt + '" />');

                // SHOW SUBMIT BUTTON IF ATLEAST "1" ELEMENT HAS BEEN CREATED.
                if (iCnt == 1) {
                    var divSubmit = $(document.createElement('div'));
                    $(divSubmit).append('<input type=button class="bt"' + 
                        'onclick="GetTextValue()"' + 
                            'id=btSubmit value=Submit />');
                }

                // ADD BOTH THE DIV ELEMENTS TO THE "main" CONTAINER.
                $('#main').after(container, divSubmit);
            }
            // AFTER REACHING THE SPECIFIED LIMIT, DISABLE THE "ADD" BUTTON.
            // (20 IS THE LIMIT WE HAVE SET)
            else {      
                $(container).append('<label>Reached the limit</label>'); 
                $('#btAdd').attr('class', 'bt-disable'); 
                $('#btAdd').attr('disabled', 'disabled');
            }
        });

        // REMOVE ONE ELEMENT PER CLICK.
        $('#btRemove').click(function() {
            if (iCnt != 0) { $('#tb' + iCnt).remove(); iCnt = iCnt - 1; }
        
            if (iCnt == 0) { 
                $(container)
                    .empty() 
                    .remove(); 

                $('#btSubmit').remove(); 
                $('#btAdd')
                    .removeAttr('disabled') 
                    .attr('class', 'bt');
            }
        });

        // REMOVE ALL THE ELEMENTS IN THE CONTAINER.
        $('#btRemoveAll').click(function() {
            $(container)
                .empty()
                .remove(); 

            $('#btSubmit').remove(); 
            iCnt = 0; 
            
            $('#btAdd')
                .removeAttr('disabled') 
                .attr('class', 'bt');
        });
    });

    // PICK THE VALUES FROM EACH TEXTBOX WHEN "SUBMIT" BUTTON IS CLICKED.
    var divValue, values = '';

    function GetTextValue() {
        $(divValue) 
            .empty() 
            .remove(); 
        
        values = '';

        $('.input').each(function() {
            divValue = $(document.createElement('div')).css({
                padding:'5px', width:'200px'
            });
            values += this.value + '<br />'
        });

        $(divValue).append('<p><b>Your selected values</b></p>' + values);
        $('body').append(divValue);
    }
</script>
</html>