开发者

jQuery and Form Object Array

This is about form input objects with same names and unknown number of clones/duplicates such as this one:

<input name="field[]" id="field[]" value="">

using jQuery, I dynamically add copies of the object which theoretically makes it look like this:

<input name="field[]" id="field[]" value="">开发者_如何学Python
<input name="field[]" id="field[]" value="">
<input name="field[]" id="field[]" value="">
<input name="field[]" id="field[]" value="">

... and so one and so forth.

Question: Could you show me do we reference such objects, say for example, with a on-change procedure.

Thanks in advanced.


It is not valid to have multiple elements with the same ID.

You can get the n-th input using:

$('input').eq(n)


I'm rather late to the party, but here's a little routine that should do the trick. It returns an object with keys that match the form input names. When the name ends in [], it treats the input something like PHP does and pushes it onto an array.

  • $elem is a jQuery object that contains the input elements (and contenteditables) to be captured.
  • options is an object that can contain a couple different keys:
    • set saveEmpty to true to save empty strings; otherwise they are passed over.
    • set onlyVisible to true to capture only visible elements; otherwise all form inputs are captured.
getFormDataFromElem = function($elem, options) {
  options = options || {};
  const vis = options.onlyVisible ? ":visible" : "";
  const formInputs = $elem.find(`:input${vis}, [contenteditable=true]${vis}`);
  const data = {};
  formInputs.each(function() {
    const $this = $(this)
    const type = $this.attr('type');
    const val = type === "checkbox" ? (this.checked ? "1" : "0")
      : ($this.is('[contenteditable=true]') ? $this.text() : this.value) ;
    const name0 = $this.attr('name');
    const doArray = name0 && name0.slice(-2) === "[]";
    const name = doArray ? name0.slice(0, -2) : name0;
    if (!name || (!options.saveEmpty && !doArray && val === "") ) {
      return;
    }
    if (doArray) {
      if (data.hasOwnProperty(name)) {
        data[name].push(val);
        return
      }
      data[name] = [val];
      return;
    }
    data[name] = val;
  });

  return data;
};

As commented previously, don't give multiple elements the same ID! (Not that brackets are allowed in IDs or class names anyway.) Besides it's preferable to use classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜