绑定对象数组用于更新/删除其特定的表单字段 [英] Binding an array of objects to their specific form fields for updating/deleting

查看:148
本文介绍了绑定对象数组用于更新/删除其特定的表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的表单数据存储到一个对象数组作为一个链接。然后就可以点击链接,填写表格与对象/数据更新或删除。

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

推荐答案

考虑使用一个命名空间为您的code,然后创建对象操作(如数组)一些通用的功能以及一些具体到表单中。
需要注意的是像棱角分明一些图书馆,反应等处理一些这方面给你,但你问手动一部分,它也可能是值得的单向一些研究,以做到这一点。

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.

下面是一个更新的样本一起玩:的http:// codepen.io / MarkSchultheiss /笔/ LNqdxK?编辑= 0010

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");
  });
});

这篇关于绑定对象数组用于更新/删除其特定的表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆