Skip to content Skip to sidebar Skip to footer

Dynamically Add/remove Fields From Array Without Breaking It In Asp.not Mvc Core Application

I am working with asp.net MVC application. I needed to add dynamic fields for a section. I am able to add those. I am also to remove dynamic text fields from the view/UI. But I am

Solution 1:

You can create some function which will get called everytime you clicked on remove button to reset your array . In this function you need to loop through all trs then using .find() get the input-box where you need to reset name and finally use attr("name", "newvalue"); to change value.

Demo Code :

$(document).ready(function() {

  //Educationvar j = 1;
  //added class to inputs
  $('a.add-recordEducation').click(function() {
    $("#Edu-2").append('<tr><td><input name="Education[' + j + '].School" type="text" class="form-control school"></td><td><input name="Education[' + j + '].Degree" type="text" placeholder="" class="form-control degree"></td><td><input name="Education[' + j + '].Interest" type="text" placeholder="" class="form-control interest" ></td><td class="text-center"><a class="btn btn-xs delete-edurecord" edu-data-id="1"><i class="la la-trash la-lg text-danger">-</i></a></td></tr>');
    j++;
  });
  $('#Edu-2').on('click', '.delete-edurecord', function() {
    $(this).parent().parent().remove();
    j--; //decremnt countresetValues(); //call to reset values
  });

  functionresetValues() {
    counter = 1; //initialze to 1//looping through tbody
    $("#Edu-2 tr").each(function() {
      //find .school class replace its name value
      $(this).find('.school').attr("name", "Education[" + counter + "].School");
      $(this).find('.degree').attr("name", "Education[" + counter + "].Degree");
      $(this).find('.interest').attr("name", "Education[" + counter + "].Interest");
      counter++; //increment count
    })
  }


});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><tableclass="table table-bordered m-0"id="tbl_posts2"><thead><tr><th>School Name</th><th>Date of Completion</th><th>Interest</th><th>Action</th></tr></thead><tbodyid="tbl_posts_body2"><trid="re-0"><td><inputasp-for="@Model.Education[0].School"type="text"placeholder=""class="form-control"></td><td><inputasp-for="@Model.Education[0].CompletionDate"type="text"placeholder=""class="form-control"></td><td><inputasp-for="@Model.Education[0].Interest"type="text"placeholder=""class="form-control"></td><tdclass="text-center"><aclass="btn btn-xs delete-edurecord"edu-data-id="1"><iclass="la la-trash la-lg text-danger">-</i></a></td></tr></tbody><tbodyid="Edu-2"></tbody></table><h2class="content-caption mb-0 d-flex justify-content-between">
  Education
  <aclass="btn-add add-recordEducation"data-added="0"><iclass="la la-plus la-lg">+</i></a></h2>

Post a Comment for "Dynamically Add/remove Fields From Array Without Breaking It In Asp.not Mvc Core Application"