Search code examples
javascriptvirtual-dommaquette

Rendering radio buttons


How do I properly define radio buttons using Maquette so the text will render? If I use a <p> element the text appears, but on a new line.

var h = maquette.h;
var dom = maquette.dom;

document.addEventListener('DOMContentLoaded', function () {
    var form = h("form", [
      h("input", {type: "radio", value: "5", name: "freq"}),
      h("p", ["5 Hz"]),
      h("input", {type: "radio", value: "10", name: "freq"}),
      h("p", ["10 Hz"]),
      h("input", {type: "radio", value: "15", name: "freq"}),
      h("p", ["15 Hz"]),
   ]);
  document.body.appendChild(dom.create(form).domNode);
});
<script src="//cdnjs.cloudflare.com/ajax/libs/maquette/2.4.1/maquette.min.js"></script>

However, if I use a <br> element, the text doesn't appear.

var h = maquette.h;
var dom = maquette.dom;

document.addEventListener('DOMContentLoaded', function () {
    var form = h("form", [
      h("input", {type: "radio", value: "5", name: "freq"}),
      h("br", ["5 Hz"]),
      h("input", {type: "radio", value: "10", name: "freq"}),
      h("br", ["10 Hz"]),
      h("input", {type: "radio", value: "15", name: "freq"}),
      h("br", ["15 Hz"]),
   ]);
  document.body.appendChild(dom.create(form).domNode);
});
<script src="//cdnjs.cloudflare.com/ajax/libs/maquette/2.4.1/maquette.min.js"></script>

What am I doing wrong?


Solution

  • The problem is with the <br> tag. Generally, it is used as an empty, self-closing tag (either <br> or <br/>). You can read more here, Permitted content - None, it is an empty element.

    You can place the text in an inline element like a <span> or event better with <label>, using id on the input and for attribute on the label. Then, place an empty <br> after each row to separate the different radio buttons.

    Here is the solution itself:

    var h = maquette.h;
    var dom = maquette.dom;
    
    document.addEventListener('DOMContentLoaded', function () {
        var form = h("form", [
          h("input", {type: "radio", value: "5", name: "freq", id: "freq1"}),
          h("label", {innerHTML: "5 Hz", "for": "freq1"}),
          h("br"),
          h("input", {type: "radio", value: "10", name: "freq", id: "freq2"}),
          h("label", {innerHTML: "10 Hz", "for": "freq2"}),
          h("br"),
          h("input", {type: "radio", value: "15", name: "freq", id: "freq3"}),
          h("label", {innerHTML: "15 Hz", "for": "freq3"}),
       ]);
      document.body.appendChild(dom.create(form).domNode);
    });
    <script src="//cdnjs.cloudflare.com/ajax/libs/maquette/2.4.1/maquette.min.js"></script>