Shark44
Shark44

Reputation: 803

Pass variable as a parameter to a jQuery anonymous function

I want to pass a variable contained in a function to its subfunction, but it isn't working. It says the value is undefined.

$('.search-input-text').keyup(function(e) {
  e.preventDefault();
  var i = $(this).attr('data-column');
  var v = $(this).val();
  
  $('#commandHistory').delay(200).queue(function(v, i) {
    alert(v);
    commandHistoryTable.columns(i).search(v).draw();
  });
});

Upvotes: 1

Views: 190

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You cannot pass parameters to jQuery's anonymous functions. The issue in your logic is because you change the scope of v within the queue handler function to be the parameter, not the value of v in the outer scope.

To address this you can simply rename the v parameter of the function to something else and use v defined in the parent scope:

$('.search-input-text').keyup(function(e) {
  e.preventDefault();
  let i = $(this).data('column');
  let v = $(this).val();
  
  $('#commandHistory').delay(200).queue(function(_, i) {
    console.log(v);
    commandHistoryTable.columns(i).search(v).draw();
  });
});

Also note the use of data() over attr() for reading the data attribute from your HTML.

Upvotes: 1

Related Questions