HTML fieldset: form attribute not working

Viewed 827

I am trying to create an HTML form is separate parts for layout reasons. As far as I understand, you can use a fieldset with a form attribute to associate the fieldset with the form, even if it’s not inside the form (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset).

However, if I have a separate fieldset with a submit button or another input in it, it doesn’t seem to work.

<form id="test">
    <input name="inside-stuff" value="Inside">
    <button type="submit">Doit Inside</button>
</form>
<fieldset form="test">
    <input name="outside-stuff" value="Outside">
    <button type="submit">Doit Outside</button>
</fieldset>

In the above snippet I have two submit buttons and two inputs. The one in the actual form works, while the one in the attached fieldset doesn’t. When I use the inside submit button, it only submits what’s in side the main form, not what is in the associated fieldset.

This may not be obvious when running the snippet, but is certainly the case when tried in real life.

What is missing to make this work?

Update 1

The problem appears to be more generic than that. I find that input elements inside an associated fieldset don’t get submitted either.

Update 2

This is not a duplicate of Submit form using a button outside the <form> tag. This question specifically refers to a fieldset element. The other doesn’t even mention it.

2 Answers

I wrote the following javascript

function control() {
  function view(i) {
    var frm = items[i].getAttribute("form");
    var fBase = document.querySelector("form[id=" + frm + "]");
    fBase.addEventListener("submit",  function(){
      var fld = document.querySelector("fieldset[form='" + this.id + "']");
      var cln = fld.cloneNode(true);
      cln.style.display = "none";
      document.getElementById(frm).appendChild(cln);         
    },true);
  }

  var items = document.querySelectorAll("FIELDSET[form]");
  
  var getter = function () {
    return this.getAttribute("form"); 
  };

  for(var i = 0; i < items.length; i++) {
    view(i);
    Object.defineProperty(items[i], 'form', {
      get: getter
    });
  }
}
window.addEventListener("load",control,true);

It's happening because the Form you have placed inside the fieldset is wrong. The form should be the parent of the fieldset in order to get it to work! The form tag should always be the parent of the fieldset.

If you place <form> and <fieldset> then it will work. The code below should do.

<form id="test">
   <input name="stuff">
   <button type="submit">Doit</button>
</form>
<form>
   <fieldset>
      <input type="text" name="stuff2">
      <button type="submit">Doit</button>
   </fieldset>
</form>

I hope this will help!

Related