Skip to content Skip to sidebar Skip to footer

Jquery And Form Object Array

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

Solution 1:

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

You can get the n-th input using:

$('input').eq(n)

Solution 2:

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}`);
  constdata = {};
  formInputs.each(function() {
    const $this = $(this)
    const type = $this.attr('type');
    constval = 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;
  });

  returndata;
};

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.

Post a Comment for "Jquery And Form Object Array"