Skip to content Skip to sidebar Skip to footer

Binding An Array Of Objects To Their Specific Form Fields For Updating/deleting

I need to store form data into an array of objects as a link. Then be able to click the link and fill the form with the objects/data to update or delete. I'm able to store the form

Solution 1:

Consider using a namespace for your code, then create some generic functions for object manipulations (like an array) as well as some specific to your form. Note that some libraries like angular, react etc. handle some of this for you, but you asked for the manual part, and it might also be worth some study on one way to do it.

Here is an updated sample to play with: http://codepen.io/MarkSchultheiss/pen/LNqdxK?editors=0010

var myApp = myApp || {};
myApp.arrayObj = {
  indexOf: function(myArray, searchTerm, property) {
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) return i;
    }
    return -1;
  },
  indexAllOf: function(myArray, searchTerm, property) {
    var ai = [];
    for (var i = 0; i < myArray.length; i++) {
      if (myArray[i][property] === searchTerm) ai.push(i);
    }
    return ai;
  },
  lookup: function(myArray, searchTerm, property, firstOnly) {
    var found = [];
    var i = myArray.length;
    while (i--) {
      if (myArray[i][property] === searchTerm) {
        found.push(myArray[i]);
        if (firstOnly) break; //if only the first 
      }
    }
    return found;
  },
  lookupAll: function(myArray, searchTerm, property) {
    returnthis.lookup(myArray, searchTerm, property, false);
  },
  remove: function(myArray, searchTerm, property, firstOnly) {
    for (var i = myArray.length - 1; i >= 0; i--) {
      if (myArray[i][property] === searchTerm) {
        myArray.splice(i, 1);
        if (firstOnly) break; //if only the first term has to be removed
      }
    }
  },
  removeByIndex: function(myArray, index) {
    myArray.splice(index, 1);
  }
};
myApp.func = {
  hasDuplicates: function(actor) {
    var allLast = myApp.arrayObj.lookup(myApp.data.actors, actor.lName, "lName", false);
    var allFirst = myApp.arrayObj.lookup(allLast, actor.fName, "fName", true);
    return !!allFirst.length;
  },
  appendActorRow: function(newActor) {
    myApp.data.actorsTable.append("<tr><td><a href='' class='update' data-actorid='" + newActor.actorId + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr>");
  },
  getActor: function() {
    var newActor = {
      fName: $("#fName").val(),
      lName: $("#lName").val(),
      gender: $("input[type=radio][name='gender']:checked").val(),
      birthDate: $("#birthDate").val(),
      action: $("#action").prop('checked'),
      comedy: $("#comedy").prop('checked'),
      drama: $("#drama").prop('checked'),
      suspense: $("#suspense").prop('checked'),
      sciencefiction: $("#sciencefiction").prop('checked'),
      horror: $("#horror").prop('checked'),
      actorId: $("#fName").data('actorid')

    }
    return newActor;
  },
  putActor: function(actor) {
    $("#fName").val(actor.fName);
    $("#lName").val(actor.lName);
    $("input[type=radio][name='gender']").val(actor.gender);
    $("#birthDate").val(actor.birthDate);
    $("#action").prop('checked', actor.action);
    $("#comedy").prop('checked', actor.comedy);
    $("#drama").prop('checked', actor.drama);
    $("#suspense").prop('checked', actor.suspense);
    $("#sciencefiction").prop('checked', actor.sciencefiction);
    $("#horror").prop('checked', actor.horror);
    $("#fName").data('actorid', actor.actorId);
  },
  addActor: function(allowDuplicates) {
    var newActor = myApp.func.getActor();
    var validActor = false;
    if (!allowDuplicates && !myApp.func.hasDuplicates(newActor)) {
      validActor = true;
    }
    if (!validActor && allowDuplicates) {
      validActor = true;
    }
    if (validActor) {
      myApp.data.lastActorId = myApp.data.lastActorId + 1;
      newActor.actorId = myApp.data.lastActorId;
      myApp.func.appendActorRow(newActor);
      myApp.data.actors.push(newActor);
    }
    return newActor;
  },
  updateRowByIndex: function(actor, index) {
    myApp.data.actorsTable.eq(index).html(actor.fName + " " + actor.lName).data("actorid", actor.actorId).addClass('update');
  },
  updateRowByActorId: function(actor, actorId) {
    var r = myApp.data.actorsTable.find('a[data-actorid="' + actorId + '"]');
    r.html(actor.fName + " " + actor.lName).data("actorid", actor.actorId).addClass('update');
  },
  clearForm: function() {
    $('#fName').val("");
    $('#lName').val("");
    $('#birthDate').val("");
    $('#form').find('input[type="checkbox"]').prop("checked", false);
    $('#form').find('input[type="radio"]').prop("checked", false);
    returnthis;
  },
  selectActor: function(e) {
    e.preventDefault();
    var selectActorId = $(this).data('actorid');
    var actor = myApp.arrayObj.lookup(myApp.data.actors, selectActorId, "actorId", true)[0];
    myApp.func.putActor(actor);
    myApp.func.setButtons("old")
  },
  updateActor: function() {
    var actor = myApp.func.getActor();
    var index = myApp.arrayObj.indexOf(myApp.data.actors, actor.actorId, "actorId", true);
    if (index != -1) {
      myApp.data.actors[index] = actor;
      myApp.func.updateRowByActorId(actor, actor.actorId);
    }
  },
  deleteActor: function() {
    var actor = myApp.func.getActor();
    var index = myApp.arrayObj.indexOf(myApp.data.actors, actor.actorId, "actorId", true);
    if (index != -1) {
      var r = myApp.data.actorsTable.find('a[data-actorid="' + actor.actorId + '"]');
      r.parents('tr').remove();
      // either will work, used the index one//  myApp.arrayObj.remove(myApp.data.actors, actor.actorId, "actorId", true);
      myApp.arrayObj.removeByIndex(myApp.data.actors, index);
    }
    myApp.func.clearForm().setButtons("new");
    // myApp.func.setButtons("new");
  },
  setButtons: function(foo) {
    // if page is new only or form is being filled with new data// show 'Add Actor' button only
    $("#addNewActor").toggle((foo === "new"));
    $("#updateActor").toggle(!(foo === "new"));
    $("#deleteActor").toggle(!(foo === "new"));
  }
};
myApp.data = {
  actors: [],
  actorsTable: $("#actorsTable"),
  lastActorId: 0
};
/* end of myApp */// Function checks state of page and shows/hides buttonsvar actorStatex = function(foo) {
  // if page is new only or form is being filled with new data// show 'Add Actor' button only
  $("#addNewActor").toggle((foo === "new"));
  $("#updateActor").toggle(!(foo === "new"));
  $("#deleteActor").toggle(!(foo === "new"));
};

var validateForm = function(e) {};

$(document).ready(function() {

  $('#results').on('click', '.update', myApp.func.selectActor);
  $("#birthDate").datepicker();
  myApp.func.setButtons("new");
  $("#addNewActor").on('click', function() {
    var addedActor = myApp.func.addActor(false);
  });
  $("#updateActor").on('click', myApp.func.updateActor);
  $("#deleteActor").on('click', myApp.func.deleteActor);
  $("#clearButton").on('click', function() {
    myApp.func.clearForm();
    myApp.func.setButtons("new");
  });
});

Solution 2:

it's because the names of your attributes in your alert doesn't match with those in your newActor object.

You should use alert(actors[row].fName) instead of alert(actors[row].fname)

By the way you could make it really simplier using your form id #actorForm

It should be something like this (I have not tested)

var actors = [], index = 0;

$("#addNewActor").click(function() {
     var newActor = $('#actorForm').serialize();

     $("#actorsTable").append("<tr><td><a href='' class='update'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");
    actors.push(newActor);
});

// select actor
$(document).on('click', '#actorsTable tr', function() {
    if(actors[$(this).index]) {
        index = $(this).index();
        var actor = actors[index];
        // populate your form
    }
});
$("#updateActor").click(function() {
    var newActor = $('#actorForm').serialize();
    actors[index] = newActor;
});
$("#deleteActor").click(function() {
    actors.splice(index, 1);
});

Post a Comment for "Binding An Array Of Objects To Their Specific Form Fields For Updating/deleting"