[SalesForce] Why can’t I have an onclick on a button element inside a form element

This is my compontent

<aura:component controller="ccContactController">
    <form>
        <button onclick="{!c.dothisthing}">do this thing</button>
    </form>
</aura:component>

This is my lightning controller

({
    dothisthing : function(component, event, helper) {

        var action = component.get('c.goToTheServer');
        action.setCallback(this, function(response) {
            if(response.getState() === 'SUCCESS') {
                alert('success');

            } else {
                alert('error = ' + JSON.stringify(response.getError()));
            }
        });
        $A.enqueueAction(action);
    }
})

This is my apex controller class

public with sharing class ccContactController {

    @AuraEnabled
    public static void goToTheServer()
    {
        system.debug('success.');
    }
}

If I run the the component and press the button I get 'error = Disconnected or Cancelled' and my page is automatically refreshed. If I put the button element outside the form element I get 'success'.

EDIT: Also wanted to say I'm using lightning out. Didn't test in other environments. When I use a div instead of a button the onclick works as expected.

Why can't I have an onclick on a button element inside a form element?

Thanks!

Best Answer

<button /> without type="button" inside a form triggers submit action when clicked. So all you have to do is add the type="button" to the button tag.

 <button type="button" onclick="{!c.dothisthing}">do this thing</button>

Also have a look at the post here it will help.

Related Topic