Activate the checkbox if the value matches the data retrieved from the database using JavaScript

Hello everyone, I could really use some assistance. I am new to JavaScript and currently have a checkbox with a random value. My goal is to automatically check the checkbox when the data from the database matches the value in the checkbox.

This is how my checkbox appears:

@foreach ($loin as $loin)
  <div class="custom-control custom-checkbox">
     <input class="custom-control-input loincode" type="checkbox" id="{{$loin->sap_code}}" name="sap_code[]" 
       value="{{$loin->sap_code}}">
     <label for="{{$loin->sap_code}}" class="custom-control-label">{{$loin->sap_code}} 
     </label>
   </div>
 @endforeach

Here is the corresponding JavaScript code:

$('.tampilModalUbahPts').on('click',function () {
    var id = $(this).data('id');
    $('.modal-body form').attr('action','/pts/'+id+'/update');
    $.ajax({
        url: '/ptspt/getubah',
        data: {id : id},
        method:'get',
        dataType : 'json',
        success: function (data) {
            $('#lbs').val(data.lbs);
            $('.loincode').attr("checked",data.loin== value);
        }
    });
});

Apologies for any grammatical errors in my English.

Answer №1

here's a solution

$('.loincode').each(function( index ) {
    $(this).attr("checked",(data.loin && data.loin.filter(x=>(x==$(this).val())).length) ? true : false);
});

var data={loin:["108591","108592"]}

$('.loincode').each(function( index ) {
     $(this).attr("checked",(data.loin && data.loin.filter(x=>(x==$(this).val())).length) ? true : false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox"  class="loincode" value="108591" />
<input type="checkbox"  class="loincode" value="108592" />
<input type="checkbox"  class="loincode" value="108593" />

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

The file "tfjs_binding.node" could not be located in the directory where @tensorflow is installed

After attempting to utilize certain functionalities of TensorFlow, I encountered an error indicating that "tfjs_binding.node" was not found in the @tensorflow installation folder. I made sure to install Python 2.7 as a prerequisite for TensorFlow and veri ...

Start a timer in CodeIgniter when a button is clicked and show the time elapsed

Just a heads up: I am currently in the learning process. While I have some experience with PHP, my knowledge of Java is very limited or non-existent. In the past, I've received negative feedback due to this lack of experience. So, here I am giving it ...

Dynamically loading JSON information into a DIV using AJAX requests

I have a list of Events in JSON format that I want to display. Below is the JSON data: [{ "event_id": "1636", "event_name": "Nitelounge supported by Mo\u00ebt &amp; Chandon", "event_start_date": "2013-05-27", "event_start_time": " ...

The failure of jQuery AJAX error callback to execute

I'm currently facing an issue with an AJAX call that I have in my code. Here's the code snippet: $.ajax({ type: "get", url: "xxx.xxx.xxx/xxx.js", dataType: 'jsonp', success: function(data) { ...

Encountering an issue while trying to modify a nested datatable within an editable datatable (Possibly an Ajax Error)

I'm trying to enable editing for a nested data table (expanded through row expansion) that is inside another editable datatable. The issue seems to be related to the ajax rowEdit event. Everything works fine when I have only one editable datatable, bu ...

Tips for transferring a variable from Next.js to a plain JavaScript file

When it comes to Canvas Dom operations in my NextJs file, I decided to include a Vanilla JS file using 'next/script'. The code for this is: <Script id="canvasJS" src="/lib/canvas.js" ></Script>. Everything seems to ...

Implementing service injection within filters in NestJS

Looking to integrate nestjs-config into the custom exception handler below: import { ExceptionFilter, Catch, ArgumentsHost, Injectable } from '@nestjs/common'; import { HttpException } from '@nestjs/common'; import { InjectConfig } fro ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

Struggling to display a PHP success message using AJAX

So I have this code where I am trying to create a form in PHP and send a message. The message is being submitted successfully, but I am facing an issue when it comes to displaying a success message. The page submits the data but does not show any output. H ...

IntelliJ coverage for backend JavaScript

Is it possible to analyze code coverage in IntelliJ without using a browser? http://www.jetbrains.com/webstorm/webhelp/monitoring-code-coverage-for-javascript.html Though there are tutorials by JetBrains on code coverage, they all seem to require a browse ...

Refreshing Database using Ajax and Linq for Improved Data Management

I've been attempting to update data using Ajax and Linq, but the Ajax call never reaches the webmethod in the code behind. Despite aligning the user class with the database and ensuring that the object names are consistent, it still fails to hit the c ...

Create a random number on the server every X interval

Context I have developed a Node.js application that generates a random number every 6 seconds and exposes it through an API. To maintain separation of concerns, I decided to encapsulate the number generation logic in a function called numberGen, stored i ...

Verify that JavaScript is capable of performing mathematical operations such as addition and multiplication successfully

When dealing with a specific set of "Strings" that represent integers in an addition operation, how can one determine if the calculation is feasible in javascript? For example: 2 + 2 (certainly possible) 20000000000000000 - 1 (impossible) 2e50 + 2e60 (i ...

Is Eval really as bad as they say... What alternative should I consider using instead?

After making an ajax request, a JSON array filled with user inputs is returned to me. The inputs have already been sanitized, and by utilizing the eval() function, I can easily generate my JavaScript object and update the page... However, there lies a dil ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

Is it possible to send fetch requests to dynamic endpoints, such as remote URLs that don't have CORS enabled? Can the http-proxy-middleware library handle using variables in endpoint targets?

Using the fetch('htp://list-of-servers') command, a list of URLs is retrieved: test1.example.com test3.example.com test5.example.com The next step involves executing a fetch() function on each of these URLs: fetch('test1.example.com' ...

Unable to locate an element on the webpage due to a JavaScript-based error, which then becomes hidden after a few seconds. (Registration form)

While completing a registration form, I encounter a hidden message after clicking on the register button. Struggling to locate this elusive element has been an ongoing challenge for me. Unfortunately, my attempts to find the element have been unsuccessful ...

Substitute the Iframe element with Ajax technology

Currently, I am working on a project where I want to include previews of various websites within my own website. Right now, I am using Iframes to load the website previews and allow users to interact with them. For SEO purposes, I have decided to replace ...

Capture data from ajax effectively by extracting and executing manipulations seamlessly

I have a project where I need to retrieve images from a database using Ajax and display them using a carousel plugin. This is the process: An image URL is saved to the database by an admin The frontend script makes an Ajax call to a PHP file and retrieve ...

What is the best way to extend a class in NestJS from another class?

I've encountered an issue while attempting to extend a class service from another class service in NestJS and utilize DI to load it in a third service. The error message I'm receiving from Nest is: Error: Nest can't resolve dependencies of ...