Utilizing TypeScript Variables within a Jquery Each Iteration

I have a variable named tableIndexNumber that I need to use in different methods. When trying to access this variable, I use "this.tableIndexNumber" and it works fine. However, I face an issue when using it inside a jQuery each loop because the HTML elements are also defined as "this" within the loop. What should be my approach in this situation?

export class TablesComponent implements OnInit {

tableIndexNumber = 1;

constructor() { }

change(col: number) {

$('#' + col).each(function () {

  if ($(this).attr('class') === 'box') {

    $(this).addClass('boxSelected');
    // here is where the problem occurs with this.tableIndexNumber ++
    
  } else {
    $(this).removeClass('boxSelected').addClass('box');
  }
});

}

Answer №1

In the past, a common practice for handling this situation was to store this in a variable before the each function was called - often naming it "context" or "that", and then using that variable. However, with the introduction of arrow functions, there is now a more elegant solution as they do not have their own this context.

UPDATE: It seems I overlooked the syntax for each. It turns out you actually require the internal this, which means an arrow function won't suffice. Instead, you can resolve this issue by storing the outer this in a variable:

export class TablesComponent implements OnInit {
    tableIndexNumber = 1;

    constructor() { }

    change(col: number) {
        const component = this;
        $('#' + col).each(function() {
          if ($(this).attr('class') === 'box') {
            $(this).addClass('boxSelected');
            component.tableIndexNumber++; 
          } else {
            $(this).removeClass('boxSelected').addClass('box');
          }
        });
    }
}

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

When clicking on the side-bar, it does not respond as expected

My website has a menu layout that features a logo on the left and an icon for the menu on the right side. When the icon is clicked, the menu slides in from the right side of the window, and when clicked again, it slides out. However, I am facing two issues ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

What is the best way to verify the success of two ajax requests?

There are two ajax requests being made to check the availability of two images. Below is the code for these ajax calls: if (result['img_one'] !== '') { var src_one = "blah-blah-one.jpg"; $.ajax({url: src_one, success: ...

generate code to automatically output the content of a website

I'm in the process of creating a program that automatically navigates to a website and prints a page. Unfortunately, I'm encountering difficulties in getting it to function properly. I've attempted using the selenium chrome driver, but with ...

Click here for a hyperlink with an underline that is the same width

As we work on our website, we want a unique feature where links are underlined when hovered over, with the underline staying the same width regardless of the length of the link text. How can we achieve this using CSS/jQuery/Javascript? ...

Concealing a division element if there is no content inside of it

As a newcomer to jQuery, I am experimenting with setting up a code that hides a div when the 'innerHTML' is null. However, my attempt using the code below is not working. Can anyone point out where I might be going wrong? if (($("#php-errors").h ...

Is there a way to increase the size of the icon without altering the dimensions of the button?

After implementing a code snippet to enable a button to copy the URL to the clipboard, I encountered an issue. Originally, the button displayed the text "copy," which changed to "copied" after clicking on it and reverted back after 2 seconds. However, I d ...

Encountering an unforeseen change in the "buttonText" attribute

I've developed a simple Vue.js component for a button. When the button is clicked, it should display the text "I have been clicked." It does work as expected, but I'm also encountering an error that reads: 49:7 error Unexpected mutation of "but ...

Vue 2 draggable does not maintain reactivity when the v-model value consists of a parent tag's iterable

Utilizing Vue 2 alongside Vuex, the incoming object gets organized into distinct sub-objects according to the classCategory value. Could it be failing because the v-model value in draggable is a key sourced from the parent tag object? <div class="c ...

Utilizing Sequelize to establish associations between tables based on non-primary key columns

Here is the code snippet: User.hasMany(UserMail, {foreignKey:'to_user_id', sourceKey:'id'}); User.hasMany(UserMail, {foreignKey:'from_user_id', sourceKey:'id'}); UserMail.belongsTo(User, {foreignKey: 'from_use ...

Pause and continue scrolling through the page with the push of a button

I have a question about a simple demo. I am looking to prevent scrolling when button1 is clicked, and then resume scrolling when button2 is clicked. Can someone guide me on how to achieve this? Check out the Fiddle here HTML: <input type='button& ...

Different approach for searching and modifying nested arrays within objects

Here is an example of the object I am working with: { userId: 111, notes: [ { name: 'Collection1', categories: [ { name: 'Category1', notes: [ {data: 'This is the first note& ...

Communication between Nodemailer and Mailgun

I keep encountering an authentication issue while trying to use Nodemailer with Mailgun. I followed the Nodemailer documentation which states compatibility with Mailgun SMTP, but unfortunately, I am consistently facing this error when executing my applicat ...

What is the best way to organize large amounts of data into an array?

I am currently working on developing a unique version of wordle using javascript and html. In order to do this, I require a comprehensive list of all possible wordle words stored in an array format. Although I have the words listed within a document contai ...

Please enter a numerical value into the input field in a JavaScript form

<script> function loop() { var input = document.getElementById('inputId').value; for (var i = 0; i < input; i++) { var result = document.getElementById('outputDiv').innerHTML ...

Removing Multiple Object Properties in React: A Step-by-Step Guide

Is there a way in React to remove multiple object properties with just one line of code? I am familiar with the delete command: delete obj.property, but I have multiple object properties that need to be deleted and it would be more convenient to do this i ...

The `react-hover` npm package functions flawlessly in the development environment despite being excluded from the production build

While working on my project, I decided to utilize the npm package react-hover and it's been effective during local development in dev build. However, when I execute the npm run build command to serve the production version, the components within the & ...

Transferring a variable after a successful jQuery call

I recently posted a similar question on Stack Overflow, but it seems like the responses there disappear quickly and I didn't receive a satisfactory answer. Personally, I find it easier to understand things when they are related directly to my own cod ...

Adding a combination of HTML and Javascript to an element can result in unexpected behavior

http://jsfiddle.net/PeKdr/ Encountering an issue when having a JavaScript variable that contains both HTML and JavaScript, resulting in unexpected behavior in the output window. Neither of the buttons - one triggering the function appendTheString() or the ...

What is the best way to execute a specific set of unit tests in Gulp-Angular using Karma?

In the midst of my AngularJS 1.4 project, fashioned through the Gulp-Angular yeoman generator, I find myself facing a dilemma. With karma and gulp settings already in place, executing gulp test runs all *.spec.js files within the project. However, my desir ...