Utilize jQuery to populate checkbox and label attributes with elements from an array

I am looking to populate attributes for 4 checkboxes and their labels from specific arrays without appending the entire markup. I have everything set up in the markup and just need to fill in the attributes based on the selection from a select menu.

var _select = $('#opt');
var _container = $('#teams');

var FF1 = [{
        display: "Week 1",
        value: "Week-1"
    },
    {
        display: "Week 2",
        value: "Week-2"
    },
    {
        display: "Week 3",
        value: "Week-3"
    },
    {
        display: "Week 4",
        value: "Week-4"
    }
];

var FF2 = [{
        display: "Week 5",
        value: "Week-5"
    },
    {
        display: "Week 6",
        value: "Week-6"
    },
    {
        display: "Week 7",
        value: "Week-7"
    },
    {
        display: "Week 8",
        value: "Week-8"
    }
];


_select.on('change', function() {
    var parent = $(this).val();
    _container.removeClass('is-hidden');

    switch (parent) {
        case 'FF1':
            weekList(FF1);
            break;
        case 'FF2':
            weekList(FF2);
            break;
        default:
            break;
    }

});

function weekList(array_list) {
    $(array_list).each(function(i) {
        console.log(array_list[i]);

    });
}
.is-hidden {
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="opt">
<option value="">Select Option</option>
  <option value="FF1">FF1</option>
  <option value="FF2">FF2</option>
</select>

<div id="teams" class="is-hidden">
    <div class="checkbox">
        <input type="checkbox" name="teams" class="ck1" id="" />
        <label for="" class="lb1"></label>
    </div>

    <div class="checkbox">
        <input type="checkbox" name="teams" class="ck2" id="" />
        <label for="" class="lb2"></label>
    </div>

    <div class="checkbox">
        <input type="checkbox" name="teams" class="ck3" id="" />
        <label for="" class="lb3"></label>
    </div>

    <div class="checkbox">
        <input type="checkbox" name="teams" class="ck4" id="" />
        <label for="" class="lb4"></label>
    </div>
</div>

Would appreciate any assistance with this!

Many thanks in advance!

Cheers!

Answer №1

Here is some code that could be useful, just make sure to replace the loop in the weekList() function.

$(array_list).each(function (i) {
    var itemId = (i + 1)
    $('.ck' + itemId).val(array_list[i].value);  // update checkbox values
    $('.ck' + itemId).attr("id", ("ck"+ itemId));    // update checkbox id
    $('.lb' + itemId).text(array_list[i].display)// update label text
    $('.lb' + itemId).attr("for",("ck"+ itemId))     // update label for text
});

Answer №2

Give This a Shot-

function displayWeek(array_list) {
  var containers = '';
  $(array_list).each(function(i) {

    containers += `
                <div class="">
                  <input type="checkbox" name="${array_list[i]['value']}" class="ck1" value="${array_list[i]['value']}" />
                  <label for="${array_list[i]['value']}" class="lb1">${array_list[i]['display']}</label>
                </div>
            `;

  });

  document.getElementById('teams').innerHTML = containers;
}

html-

<select id="opt">
  <option value="">Choose an Option</option>
  <option value="FF1">FF1</option>
  <option value="FF2">FF2</option>
</select>

<div id="teams">

</div>

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

How can I retrieve all links using XPath in Puppeteer when there are issues with pausing or functionality?

I am having issues with using XPaths to select all links on a page in my Puppeteer app. Sometimes the method I am using gets stuck and causes my crawler to pause. I'm wondering if there is a better way to retrieve all links from an XPath or if there m ...

The express-handlebars module is having trouble parsing HTML within the main layout file in an Express.js application

Hello, I am facing an issue with handlebars as it is not reading the HTML in my file. Here is a screenshot highlighting the problem along with the provided code. The folder structure is as follows: views layouts main-layout.hbs home.hbs https://i ...

Ways to generate a customized template using the directive attribute parameter

I have developed a new directive and I am looking to incorporate a dynamic template using the attribute wm.data.typeName. wm.data.typeName = "<span>html code</span>" <fill-choose model-input="wm.data.modelInput" text="wm.data.typeName"&g ...

What are some effective strategies for reducing excessive re-rendering of React components?

Here is how I am displaying a list of components on the screen: const MessagesContainer = ({ messages, categories, addHandler }) => { const options = categories.map(category => ( { value: category.name, label: category.name } )); ...

Issues with the width of Table TD cells not being responsive

I'm having trouble adjusting the width of my dropdown menu columns. I've tried various methods, but can't seem to get each column to be 200px wide as desired. .dropbtn { background-image: url("../sliki/meni.png"); width: 220px; heig ...

Customize your search experience with Google Custom Search Engine for Internet Explorer

Currently, I am integrating Google Custom Search (Business Edition) into my website using the Custom Element instead of the iFrame. I chose a theme that looks great on all browsers except for IE6. In IE6, the search results are displaying with the Promotio ...

Creating a customizable React application with an extra environmental setting

I'm currently working on an app that requires some variations. While the core remains the same, I need to customize certain parts of the app such as color schemes and images. My inquiry is: Is it feasible to construct an app with a specified instance ...

How to obliterate tinyMce completely?

I am currently working with version 3.4.b3 and have it displayed within a dialog where the content is generated dynamically. This means that the textarea tiny binds to is created each time. Therefore, when I open the dialog for the first time, tiny appear ...

Utilizing a JavaScript class within the document ready function

Having trouble with a countdown script wrapped as an object in a separate file. Struggling to setup multiple counters or objects due to the timeout function in the countdown class not finding the object that was set up within the document ready event. Wh ...

In the absence of a value

In my code, I've implemented a functionality that saves the user's input into local storage and displays it in a specific ID. However, I want to make sure that if the input field is left empty, the user is prompted to enter their name. function ...

Step-by-step guide on entering text into a hidden field with Selenium WebDriver and Java

I am currently utilizing WebDriver in conjunction with Java for automated testing. I have come across a hidden input field within the following HTML code: <input type="hidden" value="" name="body" id=":6b"> My challenge lies in trying to input data ...

Having trouble with the express-stormpath login feature for users who have authenticated with their email?

As I run a basic node.js/Express server with express-stormpath for user authentication, everything runs smoothly without email verification. However, email verification is essential for various reasons; nevertheless, my email-verified users face issues whi ...

Ionic ion-view missing title issue

I'm having trouble getting the Ionic title to display on my page: http://codepen.io/hawkphil/pen/oXqgrZ?editors=101 While my code isn't an exact match with the Ionic example, I don't want to complicate things by adding multiple layers of st ...

Repair the masthead background during overscroll

The Dilemma At the top of my webpage, I have a sleek masthead with a captivating background image that scrolls along with the page. However, there is an issue when users overscroll upwards, causing an undesirable white overflow to appear. To rectify this ...

The function cannot be called on a type that does not have a callable signature. The specified type, 'number | Dispatch<SetStateAction<number>>', does not have any compatible call signatures

Currently, I am working on setting up state to be passed through context in React using hooks. However, when I attempt to use the dispatched state updater function, an error is thrown: Cannot invoke an expression whose type lacks a call signature. Type &a ...

My data is not appearing with ng-repeat or ng-bind

One issue I am encountering is that my ng-repeat / ng-bind is not displaying the data within $scope.articles, even though I am getting the expected data in the console. To help identify the problem more easily, I have created a code snippet below: var A ...

Error message: "Property undefined when Angular attempts to call a function from jQuery/JavaScript."

I'm currently attempting to invoke an angular controller from my JavaScript code. This is my first encounter with Angular and I must admit, I'm feeling a bit overwhelmed! I've been following this example: Unfortunately, when testing it out ...

Encountering an error when using setState with React.createElement: invalid type provided

https://i.sstatic.net/YHssU.png Anticipated Outcome Upon clicking the login button without inputting an email or password, the user is expected to view the Notification component. Actual Outcome Upon clicking the login button, the setState function is ...

Top method to incorporate status verification with javascript

I need to create a system where I can monitor a specific request status from the server side. What is the most efficient method to achieve this without repeatedly sending ajax requests at predefined intervals? One idea I have is to send an ajax request to ...

Understanding the separation and communication techniques in Vue.js components

I recently developed a small vuejs application and I find myself getting confused with the functioning of components. Here is the code snippet that I have been working on: <div id="app"> <div v-if="loggedIn"> <nav> <r ...