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>