最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Adding textbox on button click using javascript - Stack Overflow

programmeradmin3浏览0评论

The following code will add new textbox on click event, but after When I click submit button the newly added textbox is not saving. please solve this issue.

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);
});

The following code will add new textbox on click event, but after When I click submit button the newly added textbox is not saving. please solve this issue.

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);
});
Share Improve this question edited Mar 22, 2016 at 12:03 apokryfos 40.7k11 gold badges80 silver badges125 bronze badges asked Mar 22, 2016 at 11:26 NivinNivin 311 gold badge2 silver badges4 bronze badges 2
  • When you add elements using javascript, then visually those elements will appear as part of form but in actual they will not be part of form submission. So on click of submit button your newly created textbox values will not be saved. Try calling an ajax method to save the values. – Cheezy Code Commented Mar 22, 2016 at 11:35
  • How to create ajax method for "added elements using javascript to save values". – Nivin Commented Mar 22, 2016 at 11:42
Add a ment  | 

7 Answers 7

Reset to default 3

Add [] to the initial text inputs name. That should solve the problem:

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

and

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

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();
});
});

Try This JsFiddle, You can dynamically add and delete table rows.

Try This

<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./ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis./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>

please try this

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

You need to first wrap your inputs in a form. Then as suggested by in other responses, change the original width and height to width[] and height[]. Also since you're already using jQuery you could use it to add the elements (not necessary though).

<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);
  });
});

Example fiddle:

https://jsfiddle/1rh480kq/1/

Try using this to call your server side method

    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');
                }
            });

Also you can refer this link to see how to use ajax and WebMethod

try

$(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);
  });
});
发布评论

评论列表(0)

  1. 暂无评论