Click the closest checkbox when the value equals the Jquery datatable

I am facing an issue where I need to add a class and click on a specific element in each row of my jQuery datatable if a certain value is equal. However, I am unable to successfully add the class to that element and trigger a click event.

<table id="userTable" class="display" width="100%">
  <thead>
    <tr>
      <th>Enable/Disable</th>
      <th>Number</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

jQuery(function($) {
  var extension = "1000";

  data = [
    ['User_488', 'User 1', 'disable'],
    ['User_487', 'User 2', 'disable'],
    ['User_477', 'User 3', 'disable'],
    ['User_490', 'User 4', 'disable'],
    ['1000', 'User 5', 'disable'],
    ['1001', 'User 6', 'enable'],
    ['1002', 'User 7', 'enable'],
    ['1004', 'User 8', 'enable']
  ]

  var t = $('#userTable').DataTable({
    "data": data,
    'columns': [{
      "render": function(data, type, row, meta) {
        var checkbox = $("<input/>", {
          "type": "checkbox"
        });
        if (row[2] === "enable") {
          checkbox.attr("checked", "checked");
          checkbox.addClass("checkbox_checked");
        } else {
          checkbox.removeAttr("checked");
          checkbox.addClass("checkbox_unchecked");
        }
        return checkbox.prop("outerHTML")
      }
    }, {
      "render": function(data, type, row, meta) {
        return row[0];
      }
    }, {
      "render": function(data, type, row, meta) {
        return row[1];
      }
    }],
    order: []
  });
  t.rows().every(function(rowIdx, tableLoop, rowLoop) {
    var data = this.data();
    var number = (t.cell(rowIdx, 0).data());
    if (number === extension) {
      console.log("[SUCCESS]: Found: " + extension);
      $(this).closest("[type=checkbox]").find('.checkbox_unchecked').addClass('clickmepls');
      var ev = document.createEvent("MouseEvents");
      ev.initEvent("click", true, true);
      document.querySelector(".clickmepls").dispatchEvent(ev);
      return false;
    }
  });

});

However, despite my efforts, I keep receiving null for the dispatch element when trying to add the class.

To view the code, please visit this JSFiddle link.

Answer №1

Give this code snippet a try:

jQuery(function($) {
  var extension = "1000";

  data = [
    ['User_488', 'User 1', 'disable'],
    ['User_487', 'User 2', 'disable'],
    ['User_477', 'User 3', 'disable'],
    ['User_490', 'User 4', 'disable'],
    ['1000', 'User 5', 'disable'],
    ['1001', 'User 6', 'enable'],
    ['1002', 'User 7', 'enable'],
    ['1004', 'User 8', 'enable']
  ]

  var t = $('#userTable').DataTable({
    "data": data,
    'columns': [{
      "render": function(data, type, row, meta) {
        var checkbox = $("<input/>", {
          "type": "checkbox"
        });
        if (row[2] === "enable") {
          checkbox.attr("checked", "checked");
          checkbox.addClass("checkbox_checked");
        } else {
          checkbox.removeAttr("checked");
          checkbox.addClass("checkbox_unchecked");
        }
        return checkbox.prop("outerHTML")
      }
    }, {
      "render": function(data, type, row, meta) {
        return row[0];
      }
    }, {
      "render": function(data, type, row, meta) {
        return row[1];
      }
    }],
    order: []
  });
  t.rows().every(function(rowIdx, tableLoop, rowLoop) {
    var data = this.data();
    var number = (t.cell(rowIdx, 0).data());
    if (number === extension) {
      nth = rowIdx + 1;
      $('#userTable tbody tr:nth-child('+nth+')').find("input[type=checkbox]").trigger('click');
      return false;
    }
  });

});

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

Unable to modify the hover color on the image or icon

After creating a circle icon with an image in the center, I wanted to make the image change colors on hover. The main focus of the icon is the circle itself. In my attempt to achieve this effect, I included the following code for the circle icon: .circle- ...

Utilize Node.js v16 for the execution of chaincode operations

Currently, I am executing JavaScript/TypeScript chaincode from fabric-samples (asset-transfer-basic/chaincode-javascript) and my requirement is to switch the Node.js version from 12 to 16. I suspect that the hyperledger/fabric-nodeenv image is specifying ...

Are there any JavaScript libraries available that can mimic SQLite using localStorage?

My current application makes use of SQLite for storage, but I am looking to switch it up to make it compatible with Firefox and other browsers. I've been considering localStorage as an option. However, I've noticed that localStorage lacks some o ...

How to send a string as a POST request using jQuery and AJAX

I am working on a custom WordPress plugin and I'm facing an issue with sending a string as POST AJAX parameters. The problem is that the string breaks whenever it encounters '&' in the code snippet below: var data = "http://localhost/wo ...

Tips for arranging HTML image sources to prepare for future updates

Incorporated into the HTML are a series of images, each accompanied by text and/or transitions. To streamline positioning, each image set along with other elements (text, video, etc...) is enclosed within a div. Furthermore, every image is labeled with a n ...

Implementing relative pathing in front-end development while using ExpressJS for the back-end

I'm currently in the process of developing an application with Express 4.14. When it comes to routing, I have a situation where the incoming request is "https://example.com/page", and I am using res.sendFile(__dirname + "/../client/pages/page/index.ht ...

What is the best way to handle the keystroke event in a $.bind method?

I'm struggling with passing a specific keystroke through the bind method. $(document).bind('keyup', event, keyup_handler(event)); This is my attempt at solving it.. Here is the function it should be passed to: var keyup_handler = functio ...

Creating unique validation rules using VeeValidate 3 and vue.js

I have a form where I need to establish specific rules. For instance, consider the following code snippet: <label class="form-label">Price range from</label> <validation-provider rules="required_if:price_to" name="Price range from" ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

What is the reason for the failure of this react ternary return statement?

My slideboard is set up to show a warning component (currently just a "test" div) when the prop "columnsItem" exceeds 50. Everything works fine, but when I switch back to a slideboard with fewer columns, all I see is a blank white screen. Can you help me ...

Arrange a collection of objects by two criteria: the end time, followed by the status in accordance with the specified array order if the end times are equal

Is this the best method to arrange data by using infinity? I gave it a try but it doesn't quite meet my requirements. data = [{ "status": "Accepted", "endTime": "" }, { "status": "New", ...

Responsive Design: Concealing a Sidebar with CSS

Seeking assistance with optimizing the layout of my app, . It currently displays a menu on the left and a login form in the center, with a graph shown to users upon logging in. Is there a way to configure it so that when accessed on iOS: 1) the left menu ...

Toggle visibility of table columns by selected options (using jQuery)

I am seeking to create a dynamic table that only shows specific columns based on the selection in a dropdown menu. <table> <thead> <td colspan="5"> <SELECT name="menu"> <option value="eur">EUR</option> & ...

Highcharts introduces shared tooltips for specific data series

I am seeking to implement specific behavior in highcharts regarding tooltips. The desired setup includes having two types of tooltips: the default shared tooltip a custom tooltip For the custom tooltip, a simple formatter can be utilized. However, the c ...

The CSS "mask" property is experiencing compatibility issues on Google Chrome

Hey there! I've recently developed a unique progress bar component in React that showcases a stunning gradient background. This effect is achieved by utilizing the CSS mask property. While everything runs smoothly on Firefox, I'm facing a slight ...

Update Personal Information with PHP and MySQL

i have two files named edit.php and update.php. The content of edit.php is as follows: <?php session_start(); $_SESSION['id'] = '9'; $id = $_SESSION["id"]; $username = $_POST["username"]; $fname = $_POST["fname"]; $password = $_POST ...

"Selecting elements with CSS using the 'element'

While exploring some websites for studying purposes, I came across this code snippet. .site-header .widget-area span.but As a beginner in CSS, I'm curious to know more about the span.but part. Is it similar to the :not pseudo selector? ...

Issue with React MUI V5 causing theme not to display properly within shadow-root element

After trying to attach the shadow root using the MUI createTheme function, I encountered rendering issues. Despite following the instructions in this helpful guide on the MUI website, my problem persists. // App.js const cache = createCache({ key: ' ...

Position two div elements side by side

Here is the HTML code snippet that I am working with: <div class="demand page"> <div id="crumby-title"> <div class="page-icon"> <i class="fa fa-line-chart"></i> </div> ...

Type inference in TypeScript with transitivity

Consider this code snippet for illustration: function foo(t: "number"): number function foo(t: "string"): string function foo(t: "boolean"): boolean function foo(t: "number" | "string ...