Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use JQuery each function in typescript

I want to get class/attr of each checkbox. Code sample is given below.

  jQuery("input[type='checkbox']").each(()=> {
      let checkboxID = jQuery(this).attr("class");
      console.log(checkboxID);//output undefined
      console.log(this.atc1List); //typescript variable 
    });
like image 329
Palash Kanti Bachar Avatar asked Jan 23 '18 08:01

Palash Kanti Bachar


1 Answers

Inside arrow function this refers to your class instance so update your code as follows, where the second argument in callback refers to the element.

jQuery("input[type='checkbox']").each((i, ele) => {
  let checkboxID = jQuery(ele).attr("class");
  console.log(checkboxID);//output undefined
  console.log(this.atc1List); //typescript variable 
});

As per MDN Docs:

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.

like image 158
Pranav C Balan Avatar answered Sep 21 '22 08:09

Pranav C Balan