A simple quick question I simply cannot figure out the answer although I went through a lot of questions here on stackoverflow. I am a newbie, so your patience is appreciated!
Here it goes: I have a function declared (hopefully) like this:
function test(parameter) {
$(parameter).trigger("click");
};
And then I want to call this function when clicked on something, like this:
$("#buttonOne").on("click", test("#correctParameter"));
Now, the issue was the function was actually executed right on the pageload and then didn't work when clicking on the #buttonOne. I read on w3school that
Function expressions will execute automatically if the expression is followed by ().<
And the truth is when I didn't use any parameter it worked only on clicking:
function test() {
$("#correctParameter").trigger("click");
};
$("#buttonOne").on("click", test);
But I have to use the parameter option so I could call on this function other times and giving it different parameter each time. Could you help me solve this?
You should call test
in a function
as follows:
$("#buttonOne").on("click", function(){
test("#correctParameter")
});
Here is an example:
function test(parameter) {
$(parameter).trigger("click");
};
$("#buttonOne").on("click", function(){
test("#correctParameter")
});
$('#correctParameter').on('click', function(){
console.log("correctParameter clicked")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="buttonOne">Click</button>
<button type="button" id="correctParameter">Other</button>