0

I'm trying to pass $(this) to a premade function. For example: clickedRows($(this)). This keeps returning undefined or 'name' is not a function. (real code below)

My question is why doesnt this work, is there a subject I could study in order to under this more?

What does work is:

`$('#rowId').on('change', function() {
  ...logic...
})`

What doesnt work is:

`function example(selectedRow) {
  ...logic...
}

$('#rowId').on('change', example($(this))`

Code:


`function clickCheckbox(selectedRow) {
  let data = discount2baproductsTable.row(selectedRow.parents('tr')).data();
  console.log('data', data) //returns undefined
  let rowIndex = discount2baproductsTable.row(selectedRow.parents("tr")).index();
  console.log('rowIndex', rowIndex) //returns undefined
  let rowCheck = cbCollectionExtraProducts[rowIndex].checked;
  const stickybar = document.getElementById("stickybar")
  // console.log(data)
  
  let product = {
    gtin: data.gtin,
    description: data.description
  }
  
  let indexNr = check(checkedRowsExtraProducts, product.gtin)
  let indexOfCheckedRow = checkedRowsExtraProducts.indexOf(product.gtin)

  // console.log('checkedRowsExtraProducts.indexOf', checkedRowsExtraProducts.indexOf(product.gtin))

  // Function that checks if gtin is already selected.
  if (!checkedRowsExtraProducts.includes(product.gtin) && rowCheck) {
      checkedRowsExtraProducts.push(product.gtin)
  } else if (indexOfCheckedRow != -1){
      checkedRowsExtraProducts.splice(indexOfCheckedRow, 1)
  }
  checkedRowsExtraProducts = [... new Set(checkedRowsExtraProducts)]
  console.log('binnen checkedRowsExtraProducts', checkedRowsExtraProducts)
  
  if(checkedRowsExtraProducts.length > 0) {
    stickybar.style.display = "block"
  } else if (checkedRowsExtraProducts.length === 0) {
    stickybar.style.display = "none"
  }
} 

$('.chkBoxExtraProducts').on('change', () => {
  clickCheckbox($(this))
})`

I tried passing regular DOM tr's and Jquery DOMs(?) tr's, both didnt work. Also tried to the event.currentTarget (which is basicly the same as $(this)).

I'm expecting to be able to reuse this functionality in different parts of the application.

  • 1
    The linked duplicate is using `setTimeout` instead of `.on()`, but the structure and problem are the same. You're executing `example($(this))` *immediately* and using its *result* as the `change` event handler. – David Nov 23 '22 at 15:34
  • 1
    Put another way: `$('#rowId').on('change', example($(this))` is the same as `var result = example($(this)); $('#rowId').on('change', result ...` – freedomn-m Nov 23 '22 at 16:38

0 Answers0