2

I had a doubt about replacing some characters in a textbox using jQuery and I landed in this question. The accepted answer suggested something like this:

$("#mySelector").val(function(i, v) { //i, v... where they come from??
return v.replace("#","Custom Text");
});

That works fine but I still have the same doubt. Those parameters, i and v. Where do they come from and how they are filled with data? They are not declared anywhere. How do i and v in this case, has the data that I need?

These answers talk about it, but it seems just an overcomplicated explanation for what should be, an easy thing to explain.

So, the question is simple. How in the world those parameters in the anonymous function, get filled with data. Where do they come from if I didn't declare them anywhere?

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
SamyCode
  • 928
  • 3
  • 14
  • 33

2 Answers2

4

They are set when the jQuery library calls the callback. Note that you are passing a function as a parameter into the $.val function. The $.val function passes values to the function that you passed to it.

Here is a simple example of how callbacks work:

function coolFunction(callback) { // accepting callback
  // extra processing here
  callback(1, 2);                 // calling the callback
}

coolFunction(function(a, b) { // passing function as callback
  console.log('annonymous', a, b);
});
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
  • 1
    This is how an answer should be written. Short, concise and easy to understand. Thank you! – SamyCode Aug 01 '17 at 18:55
  • @SamyCode, I'm glad that I could help you! Thanks for the accept. – Sumner Evans Aug 01 '17 at 18:57
  • "_The $.val function passes values to the function that you passed to it._" Is it done through the `return` statement? I mean, `val` returns two values to `function(i,v)`? – Manaus Jun 01 '21 at 19:58
0

The jQuery function val checks the argument passed into it. When it finds a function, it calls it for every element contained in the selector, where i is the index of the element in selector, and v is the value... ie the element's value.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80