The Jquery function was implemented twice in the code

I am working on a code snippet that creates progress bars for checkboxes. My goal is to have multiple progress bars on the same page. How can I trigger the function uniquely for each div?

$(window).load(function(){
$(function() {
    $("#reminder").progressbar({
        value: 0,
        max: 100,
        textFormat: 'fraction',
        complete: function(event, ui) {
            alert("Task completed successfully!");
        }
    });

    $('.option').on('change', function() {
        var total = 0;

        $('.option:checked').each(function() {
            total += parseInt($(this).val());
        });

        $("#reminder").progressbar("value", total);
    });

});
});

Here is the corresponding HTML part,

<div id="reminder"></div>  
<div>
    <input type="checkbox" class="option" value="25"> Task 1<br>
    <input type="checkbox" class="option" value="25"> Task 2<br>
    <input type="checkbox" class="option" value="25"> Task 3<br>
    <input type="checkbox" class="option" value="25"> Task 4<br>
</div>

How can I implement another div with the same functionality without causing interference and without duplicating all the JavaScript code with altered class and ID names.

Answer №1

If the container for the choices always comes after the progress bar container, you can make these adjustments in your script (use lines starting with + instead of -):

Instead of using an id, use a class "remind":

+<div class="remind"></div> 
-<div id="remind"></div>

Initialize the progress bar by class instead of id:

+$(".remind").progressbar({
-$("#remind").progressbar({

Perform a localized search for other selected options within the parent (div):

+$(this).parent().find('.option:checked').each(function() {
-$('.option:checked').each(function() {

Lastly, utilize the HTML structure to advance the progress by referring to the previous option div:
*the first sentence in my response is crucial here

+$(this).parent().prev('div.remind').progressbar("value", total);
-$("#remind").progressbar("value", total);

Welcome to Stack Overflow! [:

Check out this jsFiddle to see everything in action.

Answer №2

To effectively link the input elements to their progress bar, you have two options - either enclose them in a container or assign a data- attribute to each input element.

html

<div id="remind" class="progress-bar"></div>  
<div>
    <input type="checkbox" class="option" value="25" data-progress="remind"> Task 1<br>
    <input type="checkbox" class="option" value="25" data-progress="remind"> Task 2<br>
    <input type="checkbox" class="option" value="25" data-progress="remind"> Task 3<br>
    <input type="checkbox" class="option" value="25" data-progress="remind"> Task 4<br>
</div>
<div id="forget" class="progress-bar"></div>  
<div>
    <input type="checkbox" class="option" value="25" data-progress="forget"> Task 1<br>
    <input type="checkbox" class="option" value="25" data-progress="forget"> Task 2<br>
    <input type="checkbox" class="option" value="25" data-progress="forget"> Task 3<br>
    <input type="checkbox" class="option" value="25" data-progress="forget"> Task 4<br>
</div>

jquery

$(".progress-bar").progressbar({
    value: 0,
    max: 100,
    textFormat: 'fraction',
    complete: function(event, ui) {
        alert("Job complete you lazy bum!");
    }
});

$('.option').on('change', function() {
    var total = 0,
        progressbarID = $(this).data('progress');

    $('input[data-progress="'+progressbarID+'"].option:checked').each(function() {
        total += parseInt($(this).val());
    });

    $('#'+progressbarID).progressbar("value", total);
});

Demo at http://jsfiddle.net/kksXU/

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

Adding a Vue component to HTML using a script tag: A step-by-step guide

Scenario: I am working on creating a community platform where users can share comments. Whenever a comment contains a URL, I want to turn it into a clickable component. Challenge Statement: I have a dataset in the form of a string and my aim is to replac ...

Custom JSON filtering

I have a JSON object called Menu which contains various menu items for my system that I am developing using VueJS + Vuetify. I need to filter these menu items based on the "text" field, regardless of position in the text and without differentiating between ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

Issue with Kendo dropdown's optionLabel functionality malfunctioning

Check out the Kendo code snippet below for a dropdown control. I'm currently facing an issue where I am trying to display a "Please select" option in the dropdown. This code works perfectly fine for all other dropdowns except for this specific one. T ...

The Handsontable popup autocomplete editor is unfortunately truncated by the horizontal scrollbar

I have implemented an autocomplete feature on all columns in my project. However, I am facing an issue where the autocomplete editor gets cut off by the horizontal scrollbar. You can see the problem demonstrated in this jsfiddle link. Here is some code re ...

Identifying the presence of an image in a directory and displaying a standard image if not found

I have a directory containing pictures of different wines, each labeled with a specific code (e.g. FMP-HTR17). I would like to show the corresponding picture if it is available, but display a default image if the specific picture does not exist in the dire ...

Unable to trigger window.open function or it is not being invoked

I am facing an issue with a button on my form that generates PDF files and saves them to the local machine. I want to be able to not only save the files locally but also have them available for download in the browser, especially when there are multiple fi ...

React Navigation Error: navigateTo must be used within a valid router configuration

When attempting to utilize useNavigation() from react-router-dom, I encounter the following error: Error: useNavigation must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router. NavBar src/components/NavBar.js:6 3 ...

Tricking ASP.NET and IE8 with a Pseudo Asynchronous File Upload Method

Just a heads up, I have to cater to IE8 for a few different reasons. I've come across various methods that involve placing a file upload control inside a form element, and then using an iframe to mimic an AJAX file upload (like this one at How to make ...

What is the method for altering the date format of a published article?

I am looking to modify the date format of a published post in WordPress. Currently, the date format is <?php the_time('m.d.y'); ?></div>, which appears as "1.20.2018". My goal is to change it to "January 20, 2018". Can anyone guide ...

What is the best way to create a flexible Ul-LI menu?

Is it possible to create a flexible menu where clicking on an item does not cover other items in the menu? #demo { margin: 30px 0 50px 0; font-family: sans-serif; } #demo .wrapper { display: inline-block; width: 180px; height: 20px; position ...

Attempting to send an AJAX request to a different server (not functioning with the provided example)

UPDATE - Issue Resolved. Many thanks to everyone who provided input. After conducting extensive research, I discovered that instead of CORS, I needed to focus on JSONP all along. I have read several tutorials and believe I now have a good grasp of the con ...

Substitute numerical strings with actual numbers within an array

I need to transform an array from arr = ["step","0","instruction","1"] to newArr = ["step",0,"instruction",1] Below is the code I am using for this operation: newArr = arr.map((x) => { ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

Initiate a Gravity Forms form refresh after modifying a hidden field with jQuery

TO SUM IT UP: Is there a way in Javascript to activate an update on a Gravity Form that triggers the execution of conditional logic? ORIGINAL QUESTION: I'm using Gravity Forms and I have set up an "on change" event $('#gform_1').find(&apos ...

Unable to assign a class to the menu option

I'm encountering an issue with the following code: JavaScript $(document).ready(function() { var url = window.location; var element = $('#nav1 li a').filter(function() { return this.href == url || url.href.indexOf(this.href) == 0; ...

Unable to figure out a method to properly synchronize a vue.js asynchronous function

I am facing an issue with my code where everything works fine if I uncomment the "return" statement in fetchData. How can I make sure that I wait for the completion of this.fetchData before populating the items array? I have tried using promises, async/awa ...

What are the ways for a React Native application to communicate with a desktop computer or laptop

My goal is to establish communication between a PC and a React Native app using either Wifi or Bluetooth. I need the ability to send files from the React Native application to the PC, but I'm not sure how to accomplish this task. Are there any librari ...

How to send configuration data to an external library in Angular 6 in the app.module.ts file

My goal is to provide basic configuration settings to an external or third-party module. These settings are stored in a JSON file for easy modification across different environments without the need to rebuild the code. import { BrowserModule } from &apos ...