Show options via checkboxes

Looking to create a dynamic leaderboard for gym exercises, where users can select exercises from a database and have them appear as options in the navbar. Currently manually adding exercises, but seeking a more efficient solution using Bootstrap 5. Any tips or suggestions would be greatly appreciated!

<div class="collapse navbar-collapse justify-content-center" id="navbarCategories">
  <ul class="navbar-nav" id="navbar">
    <li class="nav-item"><a href="#squats" class="nav-link" style="color: #c5c6c8;">Squats</a></li>
    <li class="nav-item"><a href="#deadlifts" class="nav-link" style="color: #c5c6c8;">Deadlifts</a></li>
    <li class="nav-item"><a href="#benchpress" class="nav-link" style="color: #c5c6c8;">Bench Press</a></li>
    <li class="nav-item"><a href="#overheadpress" class="nav-link" style="color: #c5c6c8;">Overhead Press</a></li>
    <div class="dropdown">
      <button class="nav-link btn btn-primry dropdown-toggle" data-bs-toggle="dropdown" style="color: #c5c6c8;">Add favorite</button></li>
      <ul class="dropdown-menu">
        <form id="checkform">
          <input type="checkbox" id="benchpress" name="benchpress" value="Bench Press">
          <label for="benchpress">Bench Press</label><br>
          <input type="checkbox" id="deadlift" name="deadlift" value="Deadlifts">
          <label for="deadlift">Deadlifts</label><br>
          <input type="checkbox" id="overheadpress" name="overheadpress" value="Overhead Press">
          <label for="overheadpress">Overhead Press</label><br><br>
          <input type="submit" value="Submit">
        </form>
      </ul>
    </div>
  </ul>
</div>

Answer №1

To create a dynamic checkbox form and automatically populate the navbar options based on exercises in your database, you will require server-side scripting languages such as PHP or JavaScript. Below is a simple method using JavaScript:

  1. Retrieve the exercise list from your database.
  2. Dynamically generate the checkbox form based on the retrieved data.
  3. Use JavaScript to manage form submission and update the navbar dynamically according to selected exercises.

Here's how you can adjust your code to achieve this:

<div class="collapse navbar-collapse justify-content-center" id="navbarCategories">
    <ul class="navbar-nav" id="navbar">
        <!-- Dynamically add Navbar options here -->
        <div class="dropdown">
            <button class="nav-link btn btn-primry dropdown-toggle" data-bs-toggle="dropdown" style="color: #c5c6c8;">Add favorite</button>
            <ul class="dropdown-menu" id="exerciseList">
                <!-- Dynamically add Checkbox form here -->
            </ul>
        </div>
    </ul>
</div>

<script>
    // Simulated list of exercises (replace with actual data from database)
    const exercises = ['Squats', 'Deadlifts', 'Bench Press', 'Overhead Press'];

    // Function to dynamically generate checkbox form
    function generateCheckboxForm() {
        const exerciseList = document.getElementById('exerciseList');
        exerciseList.innerHTML = ''; // Clear existing content

        exercises.forEach(exercise => {
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = exercise.toLowerCase().replace(' ', '');
            checkbox.name = 'exercise';
            checkbox.value = exercise;
            
            const label = document.createElement('label');
            label.htmlFor = checkbox.id;
            label.textContent = exercise;

            const br = document.createElement('br');

            exerciseList.appendChild(checkbox);
            exerciseList.appendChild(label);
            exerciseList.appendChild(br);
        });
    }

    // Call function to generate checkbox form
    generateCheckboxForm();

    // Function to handle form submission
    document.getElementById('checkform').addEventListener('submit', function(event) {
        event.preventDefault(); // Prevent default form submission behavior

        const selectedExercises = [];
        const checkboxes = document.querySelectorAll('input[name="exercise"]:checked');
        checkboxes.forEach(checkbox => {
            selectedExercises.push(checkbox.value);
        });

        // Update navbar options based on selected exercises
        const navbar = document.getElementById('navbar');
        navbar.innerHTML = ''; // Clear existing navbar options

        selectedExercises.forEach(exercise => {
            const listItem = document.createElement('li');
            listItem.classList.add('nav-item');
            const link = document.createElement('a');
            link.href = '#' + exercise.toLowerCase().replace(' ', '');
            link.classList.add('nav-link');
            link.textContent = exercise;
            listItem.appendChild(link);
            navbar.appendChild(listItem);
        });
    });
</script>

Providing more specifics will aid in addressing your query effectively, including backend technology and API call methods utilized.

Remember to substitute the exercises array with real data fetched from your database using AJAX or any server-side scripting language.

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

Encountered JSON array, unable to retrieve certain attributes in AngularJS

I have developed a web service that organizes my information into a list and then converts it to JSON format. Below is the JSON output: { GetEventLTResult: [ { eventID: 1, location: "Place A", type: "Communi ...

Having difficulty accessing information from Firebase database using the .once() function

When a button is clicked on the page, I need to fetch data from a Firebase database using the once() function. Despite setting up the necessary references and variables, the data retrieval seems to be unsuccessful as the global variable numElections keeps ...

Trouble with the x-cloak attribute in alpine.js

Experience with TailwindCSS and AlpineJS in my current project has brought to my attention a slight issue with the header dropdowns flashing open momentarily when the login page loads. I attempted to use x-cloak to address this, but encountered some diffic ...

Revise shiny datatable to display total column sum differently

This is a follow up question to this inquiry: Adding Total/Subtotal to the bottom of a DataTable in Shiny. Below is the code snippet referenced: library(shiny) library(DT) ui <- shinyUI(fluidPage( h1('Testing TableTools'), mainPanel( ...

What is the best method for calculating the total of a mongoose attribute?

I am attempting to calculate the sum of schema using reduce. However, the current code is not adding the items together but rather placing them next to each other. For example, 20 + 30 should result in 50, but instead it gives me 02030. Is there an issue w ...

Steps for converting a file with JSON objects to a JSON array

I have a JSON file with multiple objects stored in a single file that I need to convert into a JSON array using JavaScript. My main objective is to create a CSV file from this data. Here is an example of the file content: { Name:"nom1", Cities:[&apos ...

Printing doesn't display CSS styling

I am currently working on creating a function to change the font color, however, I am facing issues with the CSS when it comes to printing. Here is the code I have: $('#draw').on('click', 'p', function () { if($(this).ha ...

What is the method for setting a condition within the setState function?

I used if for the title: in SetConfirmDialog, but it's not working. How can I fix this? <Button color={user.active ? "success" : "error"} variant="text" startIcon={<UserCheck />} title={user.active ? &quo ...

Creating a series of promises in a structured chain

How can the code structure be improved, especially regarding exception handling within a "promise chain"? $("#save").click(function(e) { e.preventDefault(); let $self = $(this); let profile = {} $self.prop("disabled" ...

Encountering an issue with resolving the module - Material-UI

I am encountering an issue when trying to import a component from 'Material-Ui'. I am currently working with React and Webpack. My goal is to utilize the "Card" component (http://www.material-ui.com/#/components/card). The import statement for C ...

Phaser 3 shows images as vibrant green squares

In my project, I have two scenes: Loading and Menu. In the loading scene, I load images with the intention of displaying them in the menu. Here is the code for the Loading scene: import { CTS } from './../CTS.js'; import { MenuScene } from &apo ...

What is the best way to show static files from the backend in a React application?

Currently, my setup involves a React application connected to an Express-Node.js backend through a proxy. Within the backend, there are some static files in a specific directory. When I make requests and embed the response link in the "src" attribute of an ...

What is the correct way to assign an image to a state and function?

Hello, I am new to programming and I am eager to create a function that can dynamically change 3 images based on a random number. For example, I want it to work like this: if the number generated is greater than 5, display image1; if the number is greater ...

Changing SVG containing image tags into HTML canvas

I'm attempting to convert an SVG file to an HTML canvas, and everything works perfectly until I introduce the image element in the SVG. When I include image elements, the canvg function stops working. Below is the code I used to convert the SVG to ca ...

iOS - Struggling with Multiple-to-Multiple Data Relationships?

Currently, I am in the process of developing a basic iOS app that involves setting up a database structure. The structure includes an Athlete entity that has a many-to-many relationship with Workout. The Workout entity, in turn, has a one-to-many relatio ...

Unable to retrieve information from a child component in React

So, this component acts as the main container class TaskList extends React.Component { state = { task: '', } handleTaskClick = () => { taskArray.push({id: idCount, text: this.state.task, completed: false}) idCount++ this. ...

Having trouble redirecting to the Google login screen with Passport Google Auth 2.0

Greetings, I have encountered an issue with my server setup. I am attempting to redirect users to the Google authentication screen when they navigate to the /auth/google path. However, instead of being redirected, I am consistently landing on my 404 error ...

Deactivating Webkit Input Form Shadow

Similar Question: Looking to Remove Border on Input Boxes in Chrome? Is it possible to turn off the colorful shadow effect produced by Webkit browsers when a form field is clicked? The yellow shadow in Chrome and blue shadow in Safari can interfere wi ...

Incorporating a series of image links into a Three.js project with the addition of a

My latest project involves creating a reflection cube with randomly changing images on each side every time the site is reloaded. Here is the code I have written: var imgAr = [ 'sources/instagram2/image1.jpg', 'sources/instagram2/image2.jp ...

Extract data from a JSON file and refine an array

Currently, I am working with reactjs and have an array stored in a json file. My current task involves filtering this array using the selectYear function. However, when attempting to filter the data using date.filter, I encounter the following error: An ...