2

I made this helper function to assist me with stuff

function formToObject(form) {
    var items = form.querySelectorAll("[name]");
    var json = "{";
    for (var i = 0; i < items.length; i++) {
        json += '"' + items[i].name + '":"' + items[i].value + '",';
    }
    json = json.substring(0, json.length-1) + "}";
    return JSON.parse(json);
}

There is a problem with it though, it doesn't exclude forms that are inside the form element thats passed to it. Didn't come up before but now it seems to be necessary. Is there a way to write the selector string in a way that it would exclude any children of other forms inside it?

Like "[name]:not(form *)" (which obviously doesn't work)

EDIT: got a little closer with "[name] :not(fieldset) *" but that also ignores the immediate fieldset children

user81993
  • 6,167
  • 6
  • 32
  • 64
  • Not a selector, but you could use [`Node.contains`](https://developer.mozilla.org/en/docs/Web/API/Node/contains) to filter out those element in your for loop. Btw., what sense is it supposed to make to assemble a JSON string by hand (which is not a good way to do it to begin with), only to _decode_ it then before the function returns it? If you want an array or object, then create one in the first place … – CBroe Oct 15 '15 at 21:35
  • 4
    This doesn't answer your question, but perhaps consider that [nesting forms](http://stackoverflow.com/questions/555928/is-it-valid-to-have-a-html-form-inside-another-html-form) is not valid. You should never have a "child" form. – devlin carnate Oct 15 '15 at 21:35
  • "[name]:not(form form [name])" – chiliNUT Oct 15 '15 at 21:35
  • @CBroe But how would i create the object in a generic manner if i don't know the property names beforehand? I can't use obj["someval"] etc. since the function this goes to expects an object with properties not kvp – user81993 Oct 15 '15 at 21:38
  • Basic JS knowledge: `obj["foo"] = x` can be written as `var key = "foo"; obj[key] = x` too … – CBroe Oct 15 '15 at 21:40
  • @cbroe but is obj.key = x equivalent to obj[key] = x? – user81993 Oct 15 '15 at 21:43
  • No, of course not. But you don’t need that. If you want to populate an object in your loop and use `items[i].name` as the key, then you simply use `obj[items[i].name] = …` – CBroe Oct 15 '15 at 21:43
  • @devlincarnate thanks, technically though I don't even have to use the form element since all I use it for is for identifying groups of inputs, I think I'm going to change it to some custom data value or something – user81993 Oct 15 '15 at 21:45
  • You can group them with a class, then you just do: `.class[name]` – MinusFour Oct 15 '15 at 21:46
  • I just stumbled on
    , seems like its made for this kind of stuff and should be ok with nesting?
    – user81993 Oct 15 '15 at 21:49

0 Answers0