S_R
S_R

Reputation: 1998

JQuery event listener call function by name with parameters

I have seen other questions similar to this one, but I cant seem to find the answer i'm looking for.

Is there any way of passing parameters into a named function in a JQuery event listener?

For example, I know I can do this

$('#myelement').on("change", function(){
  var value = $(this).val();   
  myFunction(value);
});

But is there any way to just pass the function name into the event listener instead?

Something like this

$('#myelement').on("change", myFunction($(this).val()));

I thought it would be straight forward to be honest, but I can't seem to find a way to do it.

Upvotes: 3

Views: 4813

Answers (3)

Kirill Simonov
Kirill Simonov

Reputation: 8481

You can pass parameters to the handler function using jQuery .on() method.

Its format is .on( events [, selector ] [, data ], handler ), where data is any object you need to pass. Later it can be accessed via event.data property in the handler.

Check this example. Note that if you just want to access $(this).val() then you don't need any parameters: myFunction is already bound to the target element, so you can use $(this).val() inside of it.

$("#i").on("change", null, "My parameter", myFunction);

function myFunction(event) {
   console.log("Parameter: " + event.data);
   console.log("$(this).val() = " + $(this).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="i"> Enter something and press Enter

Upvotes: 1

user4490801
user4490801

Reputation:

Assuming I understand what you want, one workaround I've used is to refer to functions in an array like follows

list_of_functions = [function_1,function_2];

function function_1(){
  alert("function 1 running");
}
function function_2(){
  console.dir("function 2 running");  
}

function run_function(function_index){
  return list_of_functions[function_index]();
}

$("#function_select").on("change",function(){
  run_function(this.value);  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="function_select">
  <option disabled selected>Please select a function</option>
  <option value="0">function 1</option>
  <option value="1">function 2</option>
</select>

Upvotes: 0

Raphael Cunha
Raphael Cunha

Reputation: 1114

You can use the jQuery "on" method, then invoke the click event listener and last but not least call the function that you created.

$('button').on('click', clicked);

function clicked() {
	var val = $('#one').val();
  $('.response').html('<p>Value is ' + val + '</p>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<input type="text" id="one">
<button>Click Me</button>

<p class="response"></p>

Upvotes: 2

Related Questions