Mecom
Mecom

Reputation: 411

How to add/delete 2 or more fields in a form dynamically

I would want to have two or more fields in a form to be dynamically added and deleted as per requirement. Say for, a person can have more than 1 phone numbers and more than 1 email address. The idea is to let the user add more than one phone number and email address if they have

This down below is what I did (only a rough example)

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

    var x = 0; 

    $(add_button).click(function(e){ 
        e.preventDefault();
        if(x < max_fields){ 
            x++; 
            $(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/><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--;
    })
});

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

    var x = 0; 

    $(add_button).click(function(e){ 
        e.preventDefault();
        if(x < max_fields){ 
            x++; 
            $(wrapper).append('<div><input type="text" name="text[' + x + ']"/><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--;
    })
});
//I repeated the javascript for the first field which was this
$(document).ready(function() {
    var max_fields      = 10;
    var wrapper         = $(".container1"); 
    var add_button      = $(".add_form_field"); 

    var x = 0; 

    $(add_button).click(function(e){ 
        e.preventDefault();
        if(x < max_fields){ 
            x++; 
            $(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/><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://ajax.googleapis.com/ajax/libs/jquery/2.1.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>
<div class="container2">
    <button class="add_form_field_1">Add New Field &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span></button>
    <div>
        <input type="text" name="text[]">
    </div>
</div>

And the JsFiddle.

I am not a javascript coder hence do not know if this is how you do it or is there a better way.

P.S. I asked the same question an hour ago and had to rephrase it as it was causing confusion.

Upvotes: 0

Views: 518

Answers (3)

Farhan Sahibole
Farhan Sahibole

Reputation: 341

This may help you Mecom

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>

function removeUserDetail(index)
{
    var rows=jQuery("#user_info tr").length;
    jQuery("#user_info tr:nth-child("+(index+1)+")").remove();

    if(index==(rows-1))
    {
        jQuery("#user_info tr:nth-child("+(index)+")").children().eq(4).append('<a class="mc_plus_button" id="plus_1" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a>');
    }
    jQuery("#user_info tr").each(function(i,e){
        if(i>1)
        {
            jQuery(this).children().eq(4).children().eq(0).attr("onclick","removeUserDetail("+i+");");
        }
        });
}
      function addUserDetail() {
        var row_count1 = jQuery("#user_info tr").length;
        var row_count = 0;
        jQuery(".tr_clone").each(function(index, value) {
          var rowid = jQuery(this).data('rowid');
          if (rowid > row_count) {
            row_count = rowid;
          }
        });
        row_count = row_count + 1;

        jQuery("#user_info tr").eq(row_count1 - 1).find(".mc_plus_button").remove();
        var html = '<tr class="tr_clone" data-rowid="' + row_count + '"><td>' + row_count + '</td>';
        html += '<td style="text-align: center"><input type="text" name="user_info[name][]" id="name_'+row_count+'" aria-invalid="false" /></td>';
        html += '<td style="text-align: center"><input type="text" name="user_info[email][]" id="email_'+row_count+'" aria-invalid="false" /></td>';

        html += '<td style="text-align: center"><input type="text" name="user_info[contact][]" id="contact_'+row_count+'" aria-invalid="false" /></td>';

        html += '<td><a class="mc_minus_button" id="minus_' + row_count + '" href="javascript:void();" onclick="removeUserDetail(' + row_count + ');" title="remove"><strong>&ndash;</strong></a><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td></tr>';

        jQuery("#user_info").append(html);

      }
</script>

<table id="user_info">
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Email</th>
    <th>Contact</th>
  </tr>
  <tr class="tr_clone" data-rowid="1">
    <td align="center">1</td>
    <td style="text-align: center">
      <input type="text" name="user_info[name][]" id="name_1" aria-invalid="false" />
    </td>
    <td style="text-align: center">
      <input type="text" name="user_info[email][]" id="email_1" aria-invalid="false" />
    </td>
    <td style="text-align: center">
      <input type="text" name="user_info[contact][]" id="contact_1" aria-invalid="false" />
    </td>
    <td><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td>
  </tr>

</table>

Upvotes: 0

SilverSurfer
SilverSurfer

Reputation: 4368

You can simplyfy so much your code, check this:

$(document).ready(function() {
    $("button.add_form_field").click(function(e) {
        e.preventDefault();
        var name = $(this).closest(".container").find("input:first").attr("class")
        var numInputs = $(this).closest(".container").find("input").size()
        if (numInputs < 10) {
            numInputs++;
            if (name=="mytext"){
                $(this).closest(".container").append('<div><input type="text" name="mytext[' + numInputs + ']"/><a href="#" class="delete">Delete</a></div>');
            }
            if (name=="text"){
                $(this).closest(".container").append('<div><input type="text" name="text[' + numInputs + ']"/><a href="#" class="delete">Delete</a></div>');
            }
        } else alert('You Reached the limits')
    });

    $(document).on("click", ".delete", function(e) {
        e.preventDefault();
        $(this).parent('div').remove();
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <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[1]" class="mytext">
    </div>
</div>
<div class="container">
    <button class="add_form_field">Add New Field &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span></button>
    <div>
        <input type="text" name="text[1]" class="text">
    </div>
</div>

Upvotes: 1

Sunil Dora
Sunil Dora

Reputation: 1472

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
    
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

Here is a working example, Hope this will helps you.

Upvotes: 0

Related Questions