tatty27 tatty27 - 7 months ago 8
Javascript Question

Create a jQuery function for on click

I need to create a function that I can call with .on("click")

So far I have...

jQuery.fn.extend({
createCase: function () {
alert('smeg');
}
});

$("#results").on("click", ".cancel_case_btn").createCase();


All this does is alert 'smeg' when the page opens and does nothing when the element is clicked

Answer

You need to delegate the click event on the element so that once the respective item is clicked, you can invoke the function you created to be used with jquery objects.

jQuery.fn.extend({
    createCase: function () {
            alert('smeg');
     } 
});

$("#results").on("click",".cancel_case_btn", function()
{
  $(this).createCase();
});

Example : https://jsfiddle.net/fvgLd018/3/