Home > Web Front-end > JS Tutorial > Some effective ways to create checkboxes

Some effective ways to create checkboxes

Patricia Arquette
Release: 2024-10-20 06:25:02
Original
533 people have browsed it

Some effective ways to create checkboxes

There are 3 ways to create checkbox :

  1. By direct html code
  2. By JS code, create each element, attributes, content and appendChild child to parent
  3. By JS code, with innerHTML and Template literal

By direct html code :

<div>
  <input type="checkbox" name="color" id="red">
  <label for="red">Red</label>
 </div>
 <div>
  <input type="checkbox" name="color" id="green">
  <label for="green">Green</label>
 </div>
 <div>
  <input type="checkbox" name="color" id="Blue">
  <label for="Blue">Blue</label>
 </div>
 <div>
  <input type="checkbox" name="color" id="yellow">
  <label for="yellow">Yellow</label>
 </div>
Copy after login

By JS code, create each element, attributes, content and appendChild child to parent :

<body>
    <div id="root"></div>

    <script>
      const root = document.getElementById("root");
      const colors = ["Red", "Green", "Blue", "Yellow"];
      colors.forEach((color) => {
        // create id
        const id = color;

        // create label
        const label = document.createElement("label");
        label.setAttribute("for", id);

        // create checkbox input element
        const input = document.createElement("input");
        input.type = "checkbox";
        input.name = "color";
        input.id = id;
        input.value = color;

        // appendChild child to parent
        label.appendChild(input);
        label.appendChild(document.createTextNode(color));
        root.appendChild(label);
      });
    </script>
  </body>
Copy after login

By JS code, with innerHTML and Template literal :

<body>
    <div id="root"></div>

    <script>
      const root = document.getElementById("root");
      const colors = ["Red", "Green", "Blue", "Yellow"];
      const checkbox = colors.map((color)=>`<label for="${color}">
        <input type="checkbox" name="color" id="${color}" value="${color}" >
        ${color}</label>
      `
    ).join("");

    root.innerHTML = checkbox;
    </script>
  </body>
Copy after login

The above is the detailed content of Some effective ways to create checkboxes. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template