Save the click value for future use

My appointment form is divided into separate panels.

At Step 1, if a user clicks on London (#Store1), I want to hide the Sunday and Monday options from the calendar in panel 5.

Essentially, I need to save this click event so that when the user reaches the calendar panel, it will remember not to display Sunday and Monday.

$('#store1').click(function () {
    var $store1 = $(this).data('clicked', true);
    console.log("store 1 clicked");
    $('.Sunday').hide();
    $('.Monday').hide();
});

After capturing this click event, I intend to execute it during the calendar's display.

function ReloadPanel(panel) {
    return new Promise(function (resolve, reject, Store1) {
        console.log(panel);
        console.log("finalpanel");
        panel.nextAll('.panel').find('.panel-updater').empty();
        panel.nextAll('.panel').find('.panel-title').addClass('collapsed');
        panel.nextAll('.panel').find('.panel-collapse').removeClass('in');
        var panelUpdater = $('.panel-updater:eq(0)', panel),
                panelUrl = panelUpdater.data('url');

        if (panelUpdater.length) {
            var formData = panelUpdater.parents("form").serializeObject();
            panelUpdater.addClass('panel-updater--loading');
            panelUpdater.load(panelUrl, formData, function (response, status) {
                panelUpdater.removeClass('panel-updater--loading');
                if (status == "error") {
                    reject("Panel reload failed");
                } else {
                    resolve("Panel reloaded");
                }
            });
        } else {
            resolve("no reloader");
        }
    });
}

I'm unsure if I have written this correctly, so any assistance or recommendations would be appreciated.

Thank you in advance

Answer №1

Instead of simply "storing a click", think about assigning data values to your clickable elements and saving the selected value. This way, you can make changes to the UI based on this chosen value.

Take for instance some clickable elements with specific values:

<button type="button" class="store-button" data-store-id="1">London</button>
<button type="button" class="store-button" data-store-id="2">Paris</button>
<button type="button" class="store-button" data-store-id="3">Madrid</button>

Instead of creating separate click events for each individual button and customizing the UI accordingly, create a single universal event handler that captures the clicked value. For example:

let selectedStore = -1;
$('.store-button').on('click', function () {
    selectedStore = $(this).data('store-id');
});

This way, any section with access to the selectedStore variable will know which store is currently selected. You likely have a data structure in place to decide which "days" should be displayed/hidden, right? For example, suppose you have a list of stores with their corresponding valid days:

let stores = [
  { id: 1, name: 'London', days: [2,3,4,5,6] },
  // etc.
];

Your "days" buttons could also have corresponding day ID values like so:

<button type="button" class="day-button" data-day-id="1">Sunday</button>
<button type="button" class="day-button" data-day-id="2">Monday</button>
<!--- etc. --->

You can now utilize this data to determine which buttons to display or hide. Here's an example approach:

$('.day-button').hide();
for (let i in stores) {
    if (stores[i].id === selectedStore) {
        for (let j in stores[i].days) {
            $('.day-button[data-day-id="' + stores[i].days[j] + '"]').show();
        }
        break;
    }
}

There are numerous strategies to achieve this, depending on your UX design and flow. If you need to retain data across multiple pages (even though you mentioned "panels" suggesting a single-page setup), consider using local storage to persist variables such as selectedStore as you transition between contexts.

In essence, it all boils down to organizing your data, correlating UI elements with that data, and applying logic based on that data to manage the UI components. Rather than solely altering UI elements based on user interactions, updating your data following these interactions then adjusting your UI based on this refined data is the recommended practice.

Answer №2

If you need to store data locally and access it from different parts of your code, you can utilize local storage.

To set a value:

localStorage.setItem("store1", JSON.stringify(true))

To retrieve the value: simply parse the stored JSON object like this:

JSON.parse(localStorage.getItem("store1"))

Here's an example of how to use it:

$('#store1').click(function() {
  var $store1 = $(this).data('clicked', true);
  localStorage.setItem("store1", JSON.stringify(true))
  console.log("store 1 clicked");
  $('.Sunday').hide();
  $('.Monday').hide();
});

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

Ways to find the image source using JavaScript/Jquery upon page loading?

I've scoured countless forums, yet a viable solution still eludes me. My objective is simple - upon page load, I want to gather all elements with the ".home" class and store them in an array called arr. Subsequently, the script should iterate through ...

Is it possible to apply the active class to the current list menu item in Mark using server-side techniques instead of client-side JS

When a menu item is clicked, I want to add the active class to that specific menu item. For example, if someone clicks on the contact page, the contact option in the menu should receive the active class. I am currently working with NodeJS and Koa. Below is ...

Encountered an issue while attempting to transfer data using Marak/faker.js

Does anyone see what I might be doing wrong? I'm having trouble locating the issue in my project, which is built using Meteor and React. Here is the content of my import file: import _ from 'lodash'; import faker from 'faker'; ...

Access the value of localStorage when the body has finished loading or when the document is fully

Utilizing jQuery UI 1.12.1 alongside jQuery 3.1.1, I have implemented a function to save the state of two tabs in localStorage under currentIdx: $("#tabs").tabs({ active: localStorage.getItem("currentIdx"), activate: function(event, ui) { localSto ...

Passing an array list back to the parent component in ag-grid(Vue) - A step-by-step guide

Currently, I am integrating AG Grid with Vue. My project has a specific requirement where two checkboxes are displayed using a cellRendererFramework. However, I am facing difficulties in fetching the values of these checkboxes from the row definitions. The ...

Incorporating an SVG with CSS styling from a stylesheet

After exploring various articles and questions on the topic, I am yet to find a definitive solution. I have an external file named icon.svg, and my objective is to utilize it across multiple HTML files with different fill colors and sizes for each instanc ...

React-Bootstrap Popup encounters overlay failure

While using the Tooltip without an OverlayTrigger, I encountered the following error: webpack-internal:///133:33 Warning: Failed prop type: The prop overlay is marked as required in Tooltip, but its value is undefined. The code snippet causing the issu ...

How can I incorporate an error page into this Express application?

I'm currently working on an express application that simulates a basic version of Twitter. One feature I'm trying to implement is an error page. This way, if there are any issues with the routing, users will see a friendly message instead of a g ...

A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API: let curr = { "base_currency_code": "EUR", "base_currency_name": "Euro", "amount": "10.0000", "updated_date": "2024 ...

Is there a way to enable popovers globally and also utilize the container: 'body' option simultaneously?

My Bootstrap 5 popovers seem to be missing the arrow and I suspect it's because of interference from the parent element. The documentation provides a solution by using the container: 'body' option on a single item. How can I apply this to al ...

There was an issue when trying to process the Javascript data structure with JSON.parse

Currently, I have the following data stored in a JavaScript variable: "{'Headings': [{'name': 'Behavior', 'majorTopic': 'N', 'vote': {'down': 1, 'up': 1}}, {'na ...

Instructions on how to insert a single parenthesis into a string using Angular or another JavaScript function

Currently, I am employing Angular JS to handle the creation of a series of SQL test scripts. A JSON file holds various test scenarios, each scenario encompassing a set of projects to be tested: $scope.tests = [ { "Date": "12/31/2017", "Project": ...

Is it possible to create a channel list using the YouTube API if I am not the owner of the channel? I am not getting any errors, but nothing is showing up

I am currently working on creating a channel list and playlist of videos from a Music channel that I do not own. Here is the link to the channel: https://www.youtube.com/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ/featured. My goal is to extract data from this channe ...

What is the reason behind React re-rendering child components despite passing props that have been memoized with useMemo?

While exploring this topic, I stumbled upon an answer that seems relevant: When does React re-render child component? However, my inquiry delves into a more intricate question. Why does React typically re-render child components when utilizing the useMemo ...

In React js, I wanted to display the animation specifically on the "add to bag" button for the added item

When I click the "add to bag" button, all other buttons also display the animation. How can I make sure that only the clicked button shows the animation? Any suggestions? <Table responsive> <thead> <tr> ...

Is the Vis.js network function ready to go?

Utilizing the Vis.js network library to display graphs and am curious if there is a dedicated finishedLoading event available for this object? Any suggestions or insights are appreciated! ...

Accessing form data from Ajax/Jquery in php using $_POST variables

Thank you in advance for any assistance on this matter. I'm currently attempting to utilize Ajax to call a script and simultaneously post form data. While everything seems to be working correctly, the $POST data appears to come back blank when trying ...

Arranging buttons in a row with Bootstrap 5

Struggling to align the buttons on my webpage side by side in the center, I've tried two Bootstrap 5 classes but they're not achieving the desired look: https://gyazo.com/c23f2eade4614380aec547b11e61387a https://gyazo.com/e40a678b02c9f641f746b1c ...

VueJS: Incorporating a Computed Property within a v-for Loop

Is there a way to utilize computed properties in lists while working with VueJS v2.0.2? Check out the HTML snippet below: <div id="el"> <p v-for="item in items"> <span>{{fullName}}</span> </p> </div> A ...

Error Encountered: "JSON Post Failure in ASP.net MVC resulting in 500

Whenever I attempt to send a variable to JSON on ASP.net MVC, I encounter the following error: jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error) This is my controller ...