JavaScript - Toggle Checkbox State Based on Array Values

Currently, I'm in the process of building a Laravel user management system for a project. This system will allow admins to edit any selected user who is registered on our website. Upon clicking the edit button, a modal form containing the user's details will appear, along with checkboxes for specific website permissions.

To pass the permission information, I am utilizing data parameters. The checkboxes are then marked as "checked" if the role name is found within the array of roles. However, I've encountered an issue where when viewing a user with multiple permissions, the checkboxes remain checked until the page is refreshed.

The code snippet used:

<a href="#" class="btn btn-edit" data-toggle="modal" data-target="#editModal" data-username="{{ $user->username }}" data-permissions="{{ $user->roles->pluck('name') }}" id="editUser">Edit</a>

sdfsdfsdf

    <script type="text/javascript>
        $(document).on('click', '#editUser', function() {
            $('#edit-username').val($(this).data('username'));
                var userPerms = $(this).data('permissions');

                if (userPerms.includes('Admin'))
                {
                    document.getElementById("edit-admin_perm").checked = true;
                }

                if (userPerms.includes('Captain'))
                {
                    document.getElementById("edit-captain_perm").checked = true;
                 }

          });
     </script>

I am unsure if there is a way to reset the data each time the modal is opened or if there is a different approach I should be considering. Despite searching extensively for a solution, I have not been able to find one.

Your assistance on this matter would be greatly appreciated!

Answer №1

If a user doesn't have permission, make sure to uncheck all checkboxes. One effective method is to clear all checkboxes after the button is pressed. Once all checkboxes are cleared, you can then use your algorithm to select only the checkboxes that the user has access to.

Your code should resemble the following example:

$(document).on('click', '#editUser', function() {

        // Clear all checkboxes before selecting the ones with permissions
        document.getElementById("edit-admin_perm").checked = false;
        document.getElementById("edit-captain_perm").checked = false;

        $('#edit-username').val($(this).data('username'));

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

Calculating the total sum in Vuejs when an event is triggered

I am faced with a situation where the price of a product is added to an existing total when a user increases the quantity. However, the problem lies in the fact that even if the user decreases the quantity, the price continues to increase. Solution html ...

"Exploring the power of AJAX, manipulating strings with JavaScript, and building

In the process of creating a pyramid web app, I am currently working on integrating the JavaScript markdown editor EpicEditor for editing markdown files. $.ajax({ url: "{{ request.resource_url(context) }}raw_markdown", context: document.body, ...

load images before displaying

Is there a way to preload images when they are specified within an input type in the HTML layout like this? <input type="image" src="bla.png" id="myimage1" data-url="Myurl" /> I have come across numerous examples using the img tag for preloading im ...

Determine the orientation of the object relative to the camera in threejs

I am currently facing a scenario where I need to determine the direction of an object in relation to the camera. While I have methods for detecting if an object is within the camera's view, I am now tasked with determining the directions of objects th ...

Retrieving various pieces of data in Express

After scouring through various websites, I am still unclear on how to extract multiple GET variables using Express. My goal is to send a request to a Node.JS Express server by pinging the URL with: file_get_contents('http://127.0.0.1:5012/variable1/v ...

Preserve the existing value and then check it against the updated value of a variable within JavaScript

I utilized an API that supplies me with information in JSON format, retrieved the price of a specific currency, and presented it on a screen using JavaScript. I encapsulated this process within a function that dynamically updates the information at set int ...

Exploring ways to create additional file upload fields with distinct names through JavaScript

My latest project involved creating a button that allows users to add a file upload field, a separate button to remove a file upload field, and a counter to keep track of the total number of file upload fields. However, it appears that the fields are not b ...

Encrypting and decrypting characters such as "é" using EncodeURIComponent and DecodeURIComponent functions

I am facing an issue with my web application that involves a drop-down list containing parameters with accents, such as: "Bonjour/COUCOU SPéCIALISTE/AB12345" When I select this parameter and perform a search, the resulting URL looks like this: abcdefgh. ...

Preventing access to websites through a web application using JavaScript

I am in the process of creating a web application that enables users to create a list of websites they wish to block, preventing access from their browsers. My goal is to block websites on all browsers, but I have narrowed my focus to Chrome for now. I ha ...

Using Node.js await function results in an undefined response

One issue arises when a POST call is made to /login; the const user variable ends up being assigned as undefined even though getUser() consistently returns the expected value. Interestingly, the call console.log(getUser()); located at the end of the file e ...

Package tracking static document within javascript module

I'm currently working on a project in parcel that involves three.js. It appears that I am having trouble loading a 3D model due to an incorrect path issue. My model is located in src/assets/models/mymodel.obj and I am attempting to use it within the ...

What are some strategies for blocking URL access to a controller's method in Rails 3?

My goal is to enhance my Rails 3 application by integrating Javascript/jQuery code that retrieves data from the server and updates the page based on the fetched information. I am considering implementing jQuery's $.get() method for this purpose: $.g ...

What could be the reason for my Angular component not updating its value?

component1.html : <div class="nums-display"> {{nums}} </div> TS: nums: Array<number> = [0, 1, 2, 3]; ngOnInit(): void { this.numService.getNum().subscribe((res) => { this.num = res; }); } component2.html: <div (cli ...

What are some ways I can optimize this Drupal code snippet for better performance?

I am currently working on a patch that will be submitted to the Registration Code module for Drupal. I am wondering if there is a way to write the code below more efficiently? if (module_exists('regcode_voucher')) { $cnfg = variable_get(' ...

Using jQuery to transform a JSON array within a JSON object into an array

I am attempting to convert the JSON data below: { "questions": [ { "question#1": "How much is 3+1", "correct answer": 1, "answers": { "ans#1": "5", "ans#2": "4", ...

Steer clear of displaying the latest model directly

Currently, I have a form for creating a new Model named Route. This form includes a select field called takeover, which displays all existing Routes for the user to choose from and establish a relationship with the selected Route. The issue I am facing is ...

Identify the externally-sourced element of interest

I'm attempting to apply a ScrollReveal effect to an element loaded from a separate html file called "header.html". Unfortunately, the ScrollReveal animation is not working on this particular element, while other elements within my index.html are funct ...

What is the process for converting a negative decimal number into hexadecimal format?

hex = Number(-59).toString(16) The hexadecimal value of -59 is -3b But it should actually be ffffffffffffffC5 Any assistance on this matter would be greatly appreciated! ...

When it comes to HTML and Javascript drawing, getting the positioning just right can be a challenge

I'm currently developing a control website for a drawing robot as part of a school project. However, I've been facing some challenges with the functionality of the drawing feature. Though I admit that the site lacks attention to detail, my main ...

I am encountering a problem while performing JavaScript validations

In jQuery or using the element's ID, I can validate a textbox. For example: var field = document.getElementById('tbxSearchField').value if (field == "") {alert("please enter text");} The HTML code is as follows: <input class="input" id ...