1

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();
  });
});
0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.