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

Difficulty with Launching a Modal using Jquery (jquery-3.6.1.min.js) in Conjunction with Bootstrap 5.2.3

I'm having trouble getting a modal to open with jQuery after upgrading to newer versions of JQuery and Bootstrap. Any suggestions? JQUERY CODE - $("#exampleModal").modal(); JSP CODE - I followed the code from the Bootstrap website : ...

Javascript only select values from the initial row of the table

I have a database that I am using to populate a table with results. To interact with these results, I utilize JavaScript in addition to PHP for retrieving values from the database and displaying them in the table. <table id="datatable" class="table tab ...

Transforming an AJAX call into a reusable function

My goal is to simplify my ajax calls by creating a function that can be reused. Although I'm unsure if I'm doing it correctly, I would like to attempt this approach. <script> $(document).ready(function(){ var reg_no=$("#reg_no").va ...

Incorporating a separate PHP file which includes JavaScript code

I've been struggling to make this code work. In my footer file, I have the following: footer.php: <script type="text/javascript"> $(document).ready(function(){ $.ajax({ url: '', type: 'GET', dataType: "script", success: ...

Every time I try to read a file using JavaScript, I keep running into the error: "Uncaught TypeError: fs.readFile is not a function." It's really frustrating

const fileSystem = require('fs'); fileSystem.readFile('analogData.txt', 'utf8', (error, content) => { if (error){ console.log(error); } else console.log(content); }); I am attempting to retrieve data f ...

"Implement a smooth scrolling animation on the page to automatically move a div element upward and lock

I am attempting to create a unique animation for a header div that involves moving it to the top of the screen when the user scrolls down. Once the header div reaches the top, I want it to stay fixed in that position. As the header div moves upwards, it wi ...

Creating a diagonal rectangle with a flat bottom: A step-by-step guide

Hey there, I've encountered a little issue. I managed to create a diagonal shape on my webpage similar to the one shown in this image: https://i.sstatic.net/tMgpd.png Now, what I'm aiming for is something like this: https://i.sstatic.net/xToz7.p ...

Exploring the basics of Three.js: a step-by-step guide using a shadertoy example on transforming patterns with objects

Check out this snippet, inspired by the second live example found at : html, body { height: 100%; margin: 0; } #c { width: 100%; height: 100%; display: block; } <canvas id="c"></canvas> <script type="module"> // Three.j ...

Check out the stored image from the database with the help of PHP and jQuery

I have successfully uploaded and saved several images simultaneously into a MySQL database using jQuery and PHP. This process stores the image names in the database and uploads the files to a folder on the server. Currently, I am looking to retrieve the im ...

Ways to dynamically modify the CSS attributes of a webpage during the page load event

I'm looking to incorporate the background:rgba(226, 93, 141, 0.76) attribute into the body:after psuedo-element once my page has finished loading. Below is my HTML and CSS code: <style runat="server" id="myStyle" > body:after{ position:fix ...

How to use JavaScript regular expressions to extract the content following the second-to-last occurrence of a back

I currently have a regular expression that looks like this: /^.*[\\\/]/ At the moment, it removes every single backslash from a string. However, now I need to modify it in order to capture everything after the second to last backslash. Fo ...

What is the best method for comparing two JSON objects in AngularJS?

I am working with two JSON objects. $scope.car1={"Sedan":{"Audi":["A4","A3"]},"Hatchback":{"Maruthi":["Swift"]}}; $scope.car2={"Hatchback":{"Maruthi":["Swift"]},"Sedan":{"Audi":["A3","A4"]}}; I have attempted to compare these two objects using the co ...

Struggling to make the javascript function compatible with the drop-down menu

I'm encountering issues with making my JavaScript work properly alongside my HTML. Specifically, I want the "activity" drop-down box to function in conjunction with the "city" drop-down box. For instance, if I choose "Brisbane" and then select an acti ...

Audio Playlists and Dynamic Loading with WordPress Shortcode

I'm looking to incorporate the wp_audio_shortcode() function using AJAX, and then customize the style of the audio player. However, I'm facing an issue where the HTML code returned by the AJAX request does not allow me to customize the audio play ...

Utilize jQuery to position a banner using the window.scroll function

I am trying to adjust the position of a banner as I scroll: Here is the code snippet: $(window).scroll(function(){ offset = $(window).scrollTop() + 80; var h = $(window).height(); if(offset < 80 && offset < (h - 800)) { off ...

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

I'm experiencing some strange symbols on my page that look like ''. It appears to be a problem occurring between the servlet and the Javascript. How can I resolve this issue?

After retrieving a CSV file from my servlet, I noticed that characters like 'é', 'á' or 'õ' are not displaying properly on my page. Strangely, when I access the servlet directly via browser, everything appears fine. I atte ...

Inconsistent submission of forms across different domains

I have two domains, A and B. Domain A hosts a form at A/inquire that sends a post request to B/form-submission. Domain B accepts the POST request at B/form-submission and then redirects to A/thankyou. An interesting aspect is that Domain A displays the f ...

What is the proper way to utilize $apply and $watch in the Angularjs 1.4.10 Directive Structure?

`.directive('counter', function counter() { return { scope: {}, bindToController: { count: '=' }, controller: function () { function increaseCount() { this.count++; } function decreaseCo ...

Display and Conceal Selected Choices

I have designed a simple form with two dropdown menus. Both menus have the same options: <option value='1234:0'>Closed</option> <option value='4567:2'>Open</option> <option value='6857:1'>Dead< ...