Home > Back-end >  Javascript How to Pass a parameterized function as Click Event Handler Without firing it on page loa
Javascript How to Pass a parameterized function as Click Event Handler Without firing it on page loa

Time:09-30

Problem : The function that I want to invoke only when submit button is clicked is invoked immediately on document/page load. I only want the function to fire when I click the submit button.

This function requires a formId parameter. I have many forms with different formId's I want to re-use the function and just supply the formId as argument to it. The form id will be used by some ajax call.

Example of re-using it:

buttonA.on('click', loadPageOfSelectedNavItem('#myFormIdA') );
buttonB.on('click', loadPageOfSelectedNavItem('#myFormIdB') );
buttonC.on('click', loadPageOfSelectedNavItem('#myFormIdC') );

//.. and so on..

I did some research in SO and found related questions & answers where they suggested to just supply the function name without parentheses.

As in buttonA.on('click', loadPageOfSelectedNavItem);

However, it won't work for my purpose because I need to supply/pass the formId as argument to the function.

Can you suggest possible solutions?

Below is my current code.

(function(){
    buttonA.on('click', loadPageOfSelectedNavItem('#myFormIdA')); //this fires the function on document ready
    buttonB.on('click', loadPageOfSelectedNavItem('#myFormIdB')); //this fires the function on document ready
});

function loadPageOfSelectedNavItem(formId){
    var form = $(formId);
    $.ajax({
        url : form.attr('action'),
        data: form.serialize(),
        type: "post",
        success: function(response, status, xhr){
            $('#divContainer').html(response); //response is in html format
        }, error: function(error){
            console.log(error);
        }
    });
}

Thank you.

CodePudding user response:

How about something like:

buttonA.click({id:"#myFormIdA"}, function(event) {
  loadPageOfSelectedNavItem(event.data.id)
});
  • Related