Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

javascript - 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 data as objects in an array, but can't figure out how to load it back into the form to update.

var actors = [];

var addActor = function() {

// Assigning Form values to variables
var firstN = $("#fName").val();
var lastN = $("#lName").val();
var gender = $("[name='gender']:checked").val();
var birthdate = $("#birthDate").val();
var action = $("#action").prop('checked');
var comedy = $("#comedy").prop('checked');
var drama = $("#drama").prop('checked');
var sciencefiction = $("#sciencefiction").prop('checked');
var horror =$("#horror").prop('checked');
var suspense = $("#suspense").prop('checked');

// creates newActor variable that contains an object for each input value
var newActor = {fName: firstN, lName: lastN, gender: gender, birthDate: birthdate, action: action, comedy: comedy, drama: drama, suspense: suspense, sciencefiction: sciencefiction, horror: horror}

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

actors.push(newActor);

console.log(actors);

};

Now my selector function grabs the object but I just don't know how to load it into the form to update and delete. I've been stuck on this for a few days now.

var selectActor = function(e) {
    e.preventDefault();
    var rowClicked = $(this).parent().parent();
    row = rowClicked.index();
    alert (actors[row].fName + " " + actors[row].lName + " " +    actors[row].gender + " " + actors[row].birthDate + " " + actors[row].action + " " + actors[row].comedy + " " + actors[row].drama + " " + actors[row].suspense + " " + actors[row].sciencefiction + " " + actors[row].horror);
    console.log(actors[row]);
};

Here is what I have in action so far. When I check console everything is correct with storing, and selecting, but I can't find anything that shows how to store objects into their respected form fields.

Codepen

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {
    return this.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);
    return this;
  },
  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 buttons
var 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");
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...