[Answered ]-How do I add jQuery click event to Django admin save and continue button?

2πŸ‘

βœ…

I figured this out. I had to create a hidden field with the name of the button that had been clicked and the value of the button that had been clicked and submit that field along with the form. Worked great!


EDIT (From 02/2020)

So I originally posted this Q&A years ago and haven’t been working with Django for the last few months, but I see that someone wanted my code. Working from memory and a few pieces of code I still have around, it was something like this (which is untested)…

var frm = $('form');
var chosenBtn = frm.find('[name="_save"]');
var btns = frm.find('[name="_save"], [name="_addanother"], [name="_continue"]');
btns.unbind('click.btnAssign').bind('click.btnAssign', function(e)
{
    chosenBtn = $(this);
});
frm.unbind('submit.saveStuff').bind('submit.saveStuff', function(e)
{
    // Add your own validation here. If the validation fails, you can call:
    // e.preventDefault();
    // But if it works, no need for that line. If everything works...

    frm.append(
    [
        '<input type="hidden" name="',
        chosenBtn.attr('name'),
        '" value="',
        chosenBtn.attr('value'), // or maybe chosenBtn.text()
        '" />'
    ].join(''));
});

Leave a comment