Include a nested input field and corresponding label within a div element

Using JavaScript, I am attempting to dynamically add a div containing an input and label within another div in the body. The color variable inside the JavaScript code will eventually be relocated within the file, but for clarity, it is included here. Essentially, the pseudo code structure is as follows...

div (existing in the body)
   div (created by JS)
      input (created by JS)
      label (created by JS)
   </div>

You can view what has been achieved so far on JSFiddle, and the actual code is also provided below

HTML

<html>
  <head>
    <base target="_top">
    <?!= HtmlService.createHtmlOutputFromFile('stylesheet').getContent(); ?>
  </head>
  <body onload="buildTheColors()">
  <form id="colorChoose">
  <div class="firstBox">
  <br>
    <div id="mainContainer">
    </div>
  </div>
  </form>
  </body>
  </html>

JavaScript

var toAdd = document.createDocumentFragment();

var colors = [ 
['Dark Grey', 'dark_grey', '#4d4d4d'],
['Medium Grey', 'medium_grey', '#717171'],
['Medium Dark Grey', 'medium_dark_grey', '#9a9a9a'],
['Default Grey','light_grey','#c1c1c1'],
['47th Shade of Grey', 'lighter_grey', '#e0e0e0'],

for (var i = 0; i < colors.length; i++) {

  var newDiv = document.createElement('div');
  var newInput = document.createElement('input');
  var newLabel = document.createElement('LABEL');

    newDiv.class = 'radio-item';

    newInput.type = "radio";
    newInput.id = 'I'+colors[i][1];
    newInput.name = "colorsman";
    newInput.value = colors[i][1];


    newLabel.style.background = colors[i][2];

    newDiv.appendChild(newInput);
    newDiv.appendChild(newLabel);

    toAdd.appendChild(newDiv);

   }
document.getElementById('mainContainer').appendChild(toAdd);

CSS

.radio-item {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-item input[type='radio'] {
  display: none;
}

.radio-item label {
  color: #666;
  font-weight: normal;
}

.radio-item label:before {
  content: "";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;}

.radio-item input[type=radio]:checked + label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 11px;
  left: 12px;
  content: " ";
  display: block;
  background: #004c97;
}

Answer №1

Great job, here's the update!

var toAdd = document.createElement("div");

    var colors = [ 
    ['Dark Grey', 'dark_grey', '#4d4d4d'],
    ['Medium Grey', 'medium_grey', '#717171'],
    ['Medium Dark Grey', 'medium_dark_grey', '#9a9a9a'],
    ['Default Grey','light_grey','#c1c1c1'],
    ['47th Shade of Grey', 'lighter_grey', '#e0e0e0']]

    for (var i = 0; i < colors.length; i++) {
      var newDiv = document.createElement('div');
      var newInput = document.createElement('input');
      var newLabel = document.createElement('LABEL');

        newDiv.className = 'radio-item';

        newInput.type = "radio";
        newInput.id = 'I'+colors[i][1];
        newInput.name = "colorsman";
        newInput.value = colors[i][1];


        newLabel.style.color = colors[i][2];
        newLabel.innerText=colors[i][0];
        newLabel.setAttribute("for",'I'+colors[i][1]);

        newDiv.appendChild(newInput);
        newDiv.appendChild(newLabel);

        toAdd.appendChild(newDiv);

       }
    document.getElementById('mainContainer').appendChild(toAdd);
.radio-item {
      display: inline-block;
      position: relative;
      padding: 0 6px;
      margin: 10px 0 0;
    }

    .radio-item input[type='radio'] {
      display: none;
    }

    .radio-item label {
      color: #666;
      font-weight: normal;
    }

    .radio-item label:before {
      content: "";
      display: inline-block;
      position: relative;
      top: 5px;
      margin: 0 5px 0 0;
      width: 20px;
      height: 20px;
      border-radius: 11px;
      border: 2px solid #004c97;
      background-color: transparent;}

    .radio-item input[type=radio]:checked + label:after {
      border-radius: 11px;
      width: 12px;
      height: 12px;
      position: absolute;
      top: 11px;
      left: 12px;
      content: " ";
      display: block;
      background: #004c97;
    }
<html>
      <head>
        <base target="_top">
        <?!= HtmlService.createHtmlOutputFromFile('stylesheet').getContent(); ?>
      </head>
      <body>
      <form id="colorChoose">
      <div class="firstBox">
      <br>
        <div id="mainContainer">
        </div>
      </div>
      </form>
      </body>
      </html>

Answer №2

While reviewing your code snippet, I noticed a couple of issues that need to be addressed:

  • The buildTheColors() function is missing
  • Your var colors = [ declaration is incomplete without the closing ];

Once these errors are fixed, you should see radio-inputs displaying correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2: Changing HTTP Requests

I am trying to include a single parameter in all my web requests to disable caching forcibly. My goal is to append ?v=1535DC9D930 // Current timestamp in hex to the end of each request. I am coding this in plain ES5 JS, but the documentation is in Types ...

Sharing scope variables between multiple dynamically created directives

Find my Plunkr example here: http://plnkr.co/edit/9LcYbn1468miu5McgPqR?p=preview I successfully added the form to the variable inside the options parameter, but I am looking to bind it to a different location outside of the options parameter. I have a cu ...

"Encountered a floating-point issue when trying to read an Excel file with

When a user uploads an Excel file that contains decimal, string, and Unicode characters, I am encountering an issue with floating point errors when reading certain decimal values. For instance, a number like 0.15 is being read as 0.150000000002 in some c ...

How can one guide a glTF model in the direction it is pointed using A-frame?

I have a 3D model of my customized robot loaded in an A-frame scene using version 1.0.4. Currently, I am able to rotate the robot along its x, y, z axes, but I am facing an issue where it continues to move in its original direction rather than the one it i ...

Creating static HTML files for non-static pages using Next.js SSR/ISR

While troubleshooting an issue with a specific page, I noticed that a static HTML file was created for a non-static page using Next.js. Is this expected? The page, which we will refer to as "page1," does not include the functions getStaticPaths() or getSta ...

Tips for executing a <script> whenever the properties of a component are modified

Can I automatically run a <Script/> every time the props of a react/nextjs component change? I'm currently converting markdown files to HTML using marked and, before rendering the HTML, I want to include a [copy] button on each <pre> bloc ...

Is it feasible for a JavaScript function to receive the innerHTML of the element from which it is invoked as an argument?

Is there a way to bind a function that takes a String as a parameter to a button so that it is called onclick and takes the innerHTML of the element as a parameter, without assigning the button an id or using queryselector? <button onclick="myFunct ...

I am not encountering any errors; however, upon entering the room, my bot fails to initiate creation of a new channel

const Discord = require("discord.js") const TOKEN = "I forgot to include my token here" const { Client, GatewayIntentBits } = require('discord.js'); const { MemberFetchNonceLength } = require("discord.js/src/errors/Erro ...

Issue: ENOENT - The specified file or directory cannot be found while scanning in a discord bot

Recently, I decided to try my hand at creating discord bots even though I am new to it. After watching a tutorial and copying the code, I encountered an error that has me stumped: node:internal/fs/utils:347 throw err; ^ Error: ENOENT: no such ...

Transferring information between two tables in a MongoDb database

My current database in mongo is named "sell" and it contains two tables: "Car" and "Order". In the "Car" table, there is an attribute called "price". When I run the following command in the mongo shell: db.Order.aggregate([ { $lookup: { from: ...

How can I customize the styling of Autocomplete chips in MUI ReactJS?

Trying to customize the color of the MUI Autocomplete component based on specific conditions, but struggling to find a solution. Any ideas? https://i.stack.imgur.com/50Ppk.png ...

The lua.vm.js ajax callbacks are triggering, but unfortunately, the requested data is not

After raising this issue at https://github.com/kripken/lua.vm.js/issues/5, I realized that submitting it to stackoverflow might yield a faster response due to higher exposure. To ensure clarity, I will restate my question: How can the callback data be acce ...

Is client-side JavaScript executed prior to server-side JavaScript in AJAX?

I'm curious about how client-side code interacts with server-side responses. I have a lengthy and complex piece of code that triggers a function which in turn executes some server-side code using a HTTPRequest Object, returning a string to the calling ...

Trackball's controls are not responding correctly

Recently, I have been using trackball controls and I've come across a strange bug. When I pan and then zoom out from my new position, the controls start to behave erratically, pulling towards the origin (the further I pan, the worse the issue becomes) ...

I have implemented the appropriate code to showcase a background color, yet it doesn't seem to be appearing on the screen. Additionally, I am utilizing Sass in this project

Could someone help me understand why the background color is not showing on my website? This is the CSS I am using html { font-size: 100%; -webkit-box-sizing: border-box; box-sizing: border-box; } *, *::before, *::after { -webkit-box-sizi ...

What is the process of combining JS functions with PHP echo in code?

I am currently working on creating a popout menu for an array of values that are being displayed from the database. The goal is to show the corresponding popout menu when the svg is clicked, but I am running into an issue where it only works for the first ...

What is the correct way to utilize the submit() function within this specific form?

I have a small registration form that requires validation before submission. In order to achieve this, I've developed a JavaScript function as shown below: var name = document.getElementById('name').value; var company = document.getElem ...

What causes my scene to appear black until OrbitControl is activated in ThreeJS?

What causes the scene in ThreeJS to only appear after clicking and moving the cursor? The page remains black until I interact by clicking and moving, then everything shows up. I'm stumped on what the issue could be. Any assistance would be greatly ap ...

"Hey, getting an error stating 'require is not defined' while attempting to configure the .env file. Need some help here

I am currently working on setting up a .env file to securely store the credentials for my Firebase database within a vanilla JavaScript project. Despite following various tutorials and referencing the documentation for dotenv, I continue to encounter an er ...

Resize a responsive grid of images

Within my slider, I have three slides with 3 images each. The layout consists of one large image on the left and two smaller ones on the right. To ensure responsiveness, I've used max-width: 100% on the images so they can scale down proportionally as ...