What is preventing me from using JavaScript to generate labels?

My current project involves creating dynamic input fields to filter products by color. I initially attempted static checkbox inputs for this purpose, which worked fine. Now, I want to achieve the same functionality but dynamically through JavaScript. Instead of regular checkboxes, I'm experimenting with labels showing the colors for users to click on.

However, I'm facing an issue where I can only create the first label for red and not for blue and yellow. I've inspected the CSS, checked the JS function responsible for generating inputs and labels, and explored other potential solutions.

$(document).ready(function() {
  var $products = $('.grid-products'),
    $variants = $('.grid-variants'),
    $filters = $("#filters input[type='checkbox']"),
    product_filter = new ProductFilterLevel2($products, $variants, $filters);
  product_filter.init();
});

function ProductFilterLevel2(products, variants, filters) {
  var _this = this;

  this.init = function() {
    this.addColorInputs();
    this.filters = $("#filters input[type='checkbox']");


  };
  this.addColorInputs = function() {
    var colors = ['red', 'blue', 'yellow'];;
    var filterContainer = document.createElement("div");
    filterContainer.className = "filter-attributes";

    filterContainer.setAttribute("id", "colorFilter");

    for (i = 0; i < colors.length; i++) {
      var colorInput = document.createElement("INPUT");
      colorInput.setAttribute("type", "checkbox");
      colorInput.setAttribute("name", "colour");
      var inputId = "input-" + colors[i];
      colorInput.setAttribute("id", inputId);
      colorInput.setAttribute("value", colors[i]);
      filterContainer.appendChild(colorInput);

      var label = document.createElement("label");
      label.setAttribute("for", inputId);
      var labelColor = document.createElement("div");
      labelColor.setAttribute("id", ("color-" + colors[i]));
      labelColor.className = "color-select";

      label.appendChild(labelColor);
      filterContainer.appendChild(label);

    }
    var mainFilter = document.getElementById("filters");
    mainFilter.append(filterContainer);
  }


  
}
#colorFilter {
  display: flex;
  justify-content: space-between;
}

#colorFilter input {
  display: none;
}

#colorFilter label #color-red {
  height: 30px;
  width: 30px;
}

#colorFilter label:last-child {
  margin-right: 0px;
}

#colorFilter input:checked+label {
  border: 2px solid black;
}

#colorFilter .color-select {
  height: 100%;
  width: 100%;
}

#colorFilter label div#color-red {
  background-color: red;
}

#colorFilter label div#color-blue {
  background-color: blue;
}

#colorFilter label div#color-yellow {
  background-color: yellow;
}
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

<div id='filters' class='sections'>
  <div class='filter-attributes'>
    <h4>Static filter - Working</h4>
    <input type='checkbox' name='colour' id='red' value='red'>Red</input>
    <input type='checkbox' name='colour' id='blue' value='blue'>Blue</input>

    <input type='checkbox' name='colour' id='yellow' value='yellow'>Yellow</input>
  </div>
  <h4>Dynamic filter - not working</h4>
</div>

Answer №1

When setting the red color filter to have a specific width, make sure to adjust the rest accordingly

#colorFilter label #color-red {
  height: 30px;
  width: 30px;
}

The other elements inherit width: 100%, but since the parent element has no width (it's empty), this can cause issues

To resolve this, modify the CSS as shown below:

#colorFilter label  {
  height: 30px;
  width: 30px;
}

Tip: Use Chrome Dev Tools to analyze and troubleshoot similar styling challenges.

See live example:

[JavaScript and CSS code snippets omitted for brevity]

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

Exploring the use of Angular with tables: applying classes dynamically using ngClass and repeating items using

My table is generated from a Web Service JSON, each row has a button to mark it for deletion. When you click the button, a JS alert displays the ID of the row element, and I also need to add the 'danger' bootstrap class to the row. Now, I can cap ...

Looking to adjust the positioning of text being inserted into a column - unable to utilize text-align or float properties

I'm struggling to position my text in a specific area within a column using CSS. Our app displays a price when a quantity is selected, but I can't seem to center the $14 under 'Item Total'. Even using float: center; hasn't worked f ...

Activate the dropdown menu when ul element is in focus

I am working on creating a dropdown navigation using pure CSS. I want the dropdown menu to appear when clicking on the ul. The issue I am facing is that simple ul:focus > ul does not seem to work, even though there is an anchor within it. However, the :hov ...

Tips for positioning an inner div within an outer div

Code Snippet: <div style="width: 300px; position: absolute; right: 25%; top: 5%; -webkit-box-shadow: 2px 4px 40px 0px rgba(0,0,0,0.75); -moz-box-shadow: 2px 4px 40px 0px rgba(0,0,0,0.75);box-shadow: 2px 4px 40px 0px rgba(0,0,0,0.75);"> <secti ...

Locator for finding compound text within a div class using Selenium WebDriver

I am struggling to select a specific button in the UI that shares similarities with other elements. Below is the code snippet for the button in question: <div class="ui green ok inverted button"> <i class="checkmark icon"></i> Yes </d ...

What's the alternative now that Observable `of` is no longer supported?

I have a situation where I possess an access token, and if it is present, then I will return it as an observable of type string: if (this.accessToken){ return of(this.accessToken); } However, I recently realized that the of method has been deprecated w ...

Comparing the impact of class and element selectors on CSS performance

Considering that CSS is read from right to left, I am pondering the balance between performance and readability when it comes to adding classes to HTML in order to more efficiently target elements in CSS. Additionally, I am curious about how using a gener ...

Streamlining Tailwind CSS styles in your React/Next.js components for maximum efficiency

Since implementing Tailwind CSS in my React/Next.js project, I've noticed a decrease in maintainability compared to using traditional CSS or styled-components. Previously, I could easily consolidate style changes, but now I find myself duplicating cla ...

Verify whether the user's email is registered in the database

I have a login form and I want to verify if a user's email exists in the database, but I'm not sure about the syntax for integrating Angular with Node. In my Main.js file, I have an ng-click on the submit button that triggers this function. I ex ...

Guide to making a Grid element interactive using the Link component

PostsList component is responsible for rendering a list of posts. The goal is to enable users to click on a post item and be redirected to the specific post's link. const PostsListView = ({ posts, setError, isloggedin }) => { const [redirectCre ...

Exploring the process of iterating through JSON data using JSON.parse

After making a request to my Django server for data, I utilized JSON.parse to convert the data into a JSON object. My goal is to iterate through each attribute of the object's field and execute the function createDiv on each one. function load_blog( ...

What is the best way to send a variable to a URL when a link is clicked?

Recently, I started learning PHP and ran into a challenge while working on a school project. The specific issue that I'm facing is how to pass variables to a URL when a link is clicked. Essentially, my problem involves a dropdown menu displaying diffe ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

Exploring the methods of connecting with data-checked and data-unchecked attributes in Angular

Utilizing a toggle switch, I am able to determine what text to display in the div by utilizing html attributes such as data-checked and data-unchecked. In addition, I have an Angular pipe that translates all texts on the website based on the selected lang ...

Confusing Accessibility Rules: A Guide that Leaves Me Scratching My Head

I've been reviewing a set of rules to make sure we're in compliance with the Americans with Disabilities Act. One guideline has me scratching my head: Use the title attribute when text is not accessible I'm confused - how can text be ina ...

Updating row color according to values obtained from the map function in ReactJs

I have been experimenting with various methods to change the color of table rows based on specific values within a map function. Despite trying solutions like the UseRef hook and browsing through stack overflow, I have yet to achieve success. {dat ...

Typescript - unexpected behavior when using imported JavaScript types:

I am struggling with headaches trying to integrate an automatically generated JavaScript library into TypeScript... I have packaged the JavaScript library and d.ts file into an npm package, installed the npm package, and the typings modules in the TypeScr ...

When calling `getAuth()`, an object is returned. However, upon reloading the page, the

My code is extensive, so I have only included a portion that I believe is crucial. import {getAuth} from "firebase/auth" const authFirebase = getAuth() console.log(authFirebase) const Home = () => { ... return( ... ) } Every time I ...

Issues arise when attempting to delete messages that have already been retrieved

Having trouble removing messages from a specific user without any success: bot.js client.on("message", (message) => { if (message.content === '$deleteuser') { message.channel.fetchMessages({limit: 10}).then(collec ...

How to customize the appearance of the Facebook login button alongside other login options

I'm having trouble positioning the Facebook login button in my header. It keeps appearing far to the left and below other links :) I'm currently testing it on this page: My goal is to have the button display just to the left of the login link a ...