adam78 adam78 - 1 month ago 13
C# Question

C# and Javascript - How to Add Remove Objects To A Javascript Array and Postback to Server?

I have a form where there is a section for a user to add multiple appointment dates. This section of the form has the following fields: startdate, enddate and a add button.

<form action="/someaction">
Start Date <input type="text" id="StartDate" name="StartDate"><br>
End Date: <input type="text" id="EndDate" name="EndDate"><br>
<a class="btn btn-default js-add" href="#" role="button">Add</a>

<table class="table" >
<tbody id="dates" >

</tbody>
</table>

// Other form fields

<input type="submit" value="Submit">
</form>


Each time a user adds an appointment I want to store the values in an JavaScript object array and display the number of items in the array along with details of the object added with an option to remove it from the list. Below is my initial attempt:

<script>
var appointments = [];

$(".js-add").click(function (e) {
e.preventDefault();

var startDate = $("#StartDate").val();
var endDate = ("#EndDate").val()

// What can I use to uniquely identify each object incase we need to delete???
appointments.push( { startDate: startDate , endDate: endDate });

$('<tr/>', { html: '<td >' + startDate + '</td><td>' + endDate + '</td><td><a class="js-delete" href="" data-id="">delete</a></td>'})
.appendTo($('#dates'));
}

$(".js-delete").click(function (e) {
e.preventDefault();

var id = $(this).attr("data-id");

// How do I remove the selected object from the array???
// appointments.splice(x,1);

}
</script>


How do I remove the object from the array using the array index. I have a data-id attribute on the delete link which would contain the array index.

But the array index can change each time an object is added or deleted so how can I update the data-id attribute on existing rows?

Secondly, how do I pass this object back to the server since it isn't attached to any form input field?

Some help would be appreciated?

Answer

How do I remove the object from the array. I have a data-id attribute on the delete link but what can I use to uniquely identify the object.

Because you create a new table row you need to:

  • delegate event (i.e.: $(document).on('click', '.js-delete', function (e) {)
  • use the data-id attribute to assign it the value of the index of the current element in array.
  • on deleting a row you need to rearrange the values of the data-id

How do I pass this object back to the server

You may use an hidden input field and set its value with the array value.

The snippet:

var appointments = [];

//
// delegated event
//
$(document).on('click', '.js-delete', function (e) {
  e.preventDefault();

  var id = +$(this).attr("data-id");
  appointments.splice(id, 1);
  $(this).closest('tr').remove();
  //
  // rearrange the values of data-id attributes
  //
  $('#dates tr td:nth-child(3) a').each(function(index, element) {
    var tId = +$(element).attr("data-id");
    if (tId > id) {
      $(element).attr("data-id", tId - 1);
    }
  });
});

$(function () {
  $(".js-add").click(function (e) {
    e.preventDefault();

    var startDate = $("#StartDate").val();
    var endDate = $("#EndDate").val();

    // In order to uniquely identify each object you can set the
    // value of data-id attribute with current array index
    appointments.push( { startDate: startDate , endDate: endDate });

    $('<tr/>', { html: '<td >' + startDate + '</td><td>' + endDate + '</td><td><a class="js-delete" href="" data-id="' + (appointments.length - 1) + '">delete</a></td>'})
    .appendTo($('#dates'));

    //
    // a possible sorting.... Consider to use a date compare
    // instead of a string compare function.
    //
    $.each($('#dates tr').get().sort(function(a, b) {
      return a.childNodes[0].textContent.localeCompare(b.childNodes[0].textContent);
    }), function(index, ele) {
      $('#dates').append(ele);
    });
  });

  //
  // On form submit stringify your array and save it into
  // an hidden input field
  //
  $('input[type="submit"]').on('click', function(e) {
    e.preventDefault();
    $('#appointments').val(JSON.stringify(appointments));
    console.log($('#appointments').val());
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>


<form action="/someaction">
    <input id="appointments" type="hidden">
    Start Date <input type="text" id="StartDate" name="StartDate"><br>
    End Date: <input type="text" id="EndDate" name="EndDate"><br>
    <a class="btn btn-default js-add" href="#" role="button">Add</a>
    <table class="table" >
        <tbody id="dates" >

        </tbody>
    </table>

    <!-- Other form fields -->

    <input type="submit" value="Submit">
</form>

Comments