How to differentiate two different submit buttons in a single form

Hi,

I am very new to meteor and decided to learn, and build a simple invoice app on the go.

I have an invoice form that has an option to either send or save a new invoice into the “Invoice” mongo collection.

I do:

Templates.newInvoice.events({
    'submit .js-new-invoice' : function(e) {
        e.preventDefault();
        let invoiceObject = {}
        //I collect the required data using e.currentTarget.xyz and store in invoiceObject variable
        invoiceObject.status = "sent"
        Meteor.call('createInvoice', invoiceObject);
    } 
});

Now I have one more button in the form that will have invoiceObject.status = “saved”

How can I check if the submission was done using the send button or the save button?

Thanks

Your submit button provides the default action for form submission, but there’s nothing stopping you defining an “ordinary” button for your other action. Give it a unique class to identify it and use something like:

 'click button.other-class' : function(e) {
   // code here
 } 

Correction:

'click button.other-class' : function(e) {
   // code here
 }

So what this does is instead of listening to the submit event of the form, it listens to the click event of the button.
Or if that causes duplicate code, you can do something like this, and set up an event for all buttons in the form, and then checking their properties:

'click #myForm button' : function(e) {
    e.preventDefault();
    if($(e.target).prop('id') == 'save'){
        //Do stuff
    } else {
        //Do other stuff
    }
 }
1 Like

Very clean solution!

But now I am unable to access all the values from the form inputs?

'click button.other-class' : function(e) {
    console.log(e.target.someInputField.value); //return undefined
 }

Good catch - thanks! Comms problem between brain and fingers.

Ah yeah, the button is now the target instead of the form.
So you need to do console.log($('#myInput').val()); or something like that.

Btw, another issue I’ve come across is if you put an icon or something in a button, and click the icon, the button click event will still trigger but the icon will be the target. This can easily be fixed with the CSS rule

button *{
    pointer-events:none;
}

This basically makes all elements inside buttons transparent to clicks, so the clicks go through and hit the button instead.

Thanks for the deep insight!

The solutions seems to work for the given problem. However, since now that I am not using the form submit event, all the form validation that was happening in HTML5 will not work. Will have to take care of that with JQuery as well.

Nevermind, I just added $("#invoiceForm").validate() and it works fine! :slight_smile: