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

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

How can I fetch and reference multiple local JSON files in Vue using Axios?

I am currently utilizing vue for prototyping some HTML components. Is there a method to make Vue detect two separate JSON files? vue.js var vm = new Vue({ el: '#douglas-laing', data: { products: [], contentPanels: [] }, created() ...

Managing the AJAX response from a remote CGI script

I'm currently working on a project that involves handling the response of a CGI script located on a remote machine within a PHP generated HTML page on an apache server. The challenge I am facing relates to user authentication and account creation for ...

What is the best method for adding a header to a dynamically created table using JavaScript?

After receiving JSON data in my JavaScript, I have successfully converted it into an HTML table. Everything seems to be working fine, but I'm wondering how I can add a header to my table? Below is the code snippet: <script> $(document ...

Encountering ENOENT error with Node.js file preview

I am attempting to utilize the filepreview tool to extract an image from a docx document. I have successfully installed it using the command npm install filepreview. This is the code snippet I am working with: const filepreview = require('fileprevie ...

Is there a way in Jquery to remove a class?

I have created a code for a single page website where clicking on the toggle bar will display the 'ul' and clicking on one of the 'a' links will take me to the corresponding div. I want the toggle bar to automatically close back after c ...

Making a single variable object as opposed to using multiple variables

In order to improve the code structure, I am looking to consolidate all properties into a JavaScript object instead of using multiple variables: // Method 1 // This method gives an error as _inp cannot be accessed by input_value // Uncaught TypeError: Can ...

Following my ajax submission, the functionality of my bootstrap drop-down menu seems to have been compromised

I'm having an issue with my login page. After implementing Ajax code for the reset password feature, the dropdown menu on the login page doesn't work properly when wrong details are entered and the page reloads. I've tried using the $(' ...

"Troubleshooting WordPress website: issues with CSS and images not

I recently developed a custom WordPress theme and everything was working perfectly on my local machine. However, when I moved the theme to the server, the CSS and images are not displaying properly. Strangely enough, when I checked the 'view source&ap ...

"An innovative social media platform feature resembling a Linkedin/Facebook post box

I am looking to develop a post box feature similar to LinkedIn and Facebook. When a URL is pasted into the box, I want a thumbnail to be generated. Two main questions: - Is there an existing component that already does this? I have searched extensively b ...

Is it possible to Use Vuejs 2 to Update MathJax dynamically?

Just figured out how to resolve this issue. Simply bind the data using v-html <div id="app"> <h1 v-html="equation"></h1> <button @click='change'>Change</button> </div> var vm ...

How can I successfully implement the Add To Calendar Button Package?

Recently, I decided to incorporate this particular component into my application. Although it seemed simple enough at first, I'm now faced with a puzzling TypeError originating from within the package. The react component I am constructing is as foll ...

Error encountered: EPERM when attempting to rename a directory in Node.js unexpectedly

There is a requirement for me to remove the Backup folder, rename the processor as Backup, create a Processor folder again, and send a response to the user. The code I am using for this task is as follows: fsExtra.remove('app/Backup', function(e ...

Obtain the real-time inventory quantity of the specific product variation in WooCommerce

When a WooCommerce product variation's stock quantity is 0 or less and backorders are allowed, I want to offer customers the option to pre-order the item on the product page. To clearly indicate this to customers, the "Add to Cart" button should chan ...

Searching for a different method in JavaScript that can add items without duplication, as the prependTo function tends to insert multiple items

Every time my code runs successfully, a success message is generated and displayed using prependTo within the HTML. However, the issue arises when the user performs the successful action twice, resulting in two success messages being shown on the screen. ...

Exploring AngularJS unit testing: integrating async and await with Jasmine

I'm currently facing a challenge with unit testing my Angular service using the async/await keywords in the respective (Jasmine) unit tests below. The test for the built-in Promise is functioning correctly, however, I am encountering difficulties in g ...

Unable to make jQuery animate top function work

I have three rectangles set up like this. I've managed to make them disappear when clicking the close button on the right side of each rectangle, but I'm struggling with getting the remaining rectangles to move upward to fill the empty space. Her ...

Adding 2-dimensional text to a specified location with the help of three.js

let startPosition = new THREE.Vector3(-5,0,0); let targetPosition = new THREE.Vector3(-5,2,0); let directionVector = new THREE.Vector3().sub(targetPos,startPosition); let arrowHelper = newTHREE.ArrowHelper(directionVector.clone().normalize(),startPosition, ...

Automatically execute JavaScript upon loading the page with the option to value run on

Upon loading the page, Week 1 is automatically selected which is great. However, the javascript function only runs when I manually choose an option. I want the javascript to automatically trigger for week 1 without needing manual selection. Any ideas on ...

Tips for adjusting the font size of a Chip using Material-UI

I am using a widget called Chip const styles = { root:{ }, chip:{ margin: "2px", padding: "2px" } } const SmartTagChip = (props) =>{ const classes = useStyles(); return( <Chip style={{color:"white&q ...