3

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);
});
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. Commented Mar 22, 2016 at 11:35
  • How to create ajax method for "added elements using javascript to save values". Commented Mar 22, 2016 at 11:42

7 Answers 7

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="" />
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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.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>

Comments

1

please try this

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

Comments

1

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.net/1rh480kq/1/

2 Comments

When I refresh the page the saved textboxes are disappears..how to solve this issue
@Nivin That's way beyond the scope of this question as this requires the use of server side technology and knowing what your code does. The idea is to dynamically populate the <inputs> using a server side language (I'll assume you're using PHP) e.g. <td id="container_width"> <?php foreach ($results as $result) echo "<input type=...>" ?> </td>. You can probably find more sources on how to do this online.
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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.