function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
PenelopePenelope 

Call a function in the controller on enter keypress in Lightning?

How do you call a function in the controller/click a button when the user presses the enter key? I have a form with a submit button, all inside the same component. Thanks!
Best Answer chosen by Penelope
KristofferGreeneKristofferGreene

You could do it the old fashioned way:


Form.cmp

<aura:component implements="force:appHostable">
	<div style="text-align: center;" onkeyup="{!c.formPress}">
		<ui:inputText aura:id="firstName" label="First Name" />
		<ui:inputText aura:id="lastName" label="Last Name" />
		<ui:button label="Submit" press="{!c.buttonPress}" />
	</div>
</aura:component>
FormController.js
({
	formPress: function(component, event, helper) {
		if (event.keyCode === 13) {
			helper.submitForm(component);
		}
		//$A.log(event);
	},
	buttonPress: function(component, event, helper) {
		helper.submitForm(component);
	}
})
FormHelper.js
({
	submitForm: function(component) {
		var firstName = component.find('firstName').get('v.value'),
			lastName = component.find('lastName').get('v.value'),
			toastEvent = $A.get("e.force:showToast");
	    toastEvent.setParams({
    		title: 'Welcome ',
    		message: firstName + ' ' + lastName + '!'
	    });
	    toastEvent.fire();
	}
})

All Answers

KristofferGreeneKristofferGreene

You could do it the old fashioned way:


Form.cmp

<aura:component implements="force:appHostable">
	<div style="text-align: center;" onkeyup="{!c.formPress}">
		<ui:inputText aura:id="firstName" label="First Name" />
		<ui:inputText aura:id="lastName" label="Last Name" />
		<ui:button label="Submit" press="{!c.buttonPress}" />
	</div>
</aura:component>
FormController.js
({
	formPress: function(component, event, helper) {
		if (event.keyCode === 13) {
			helper.submitForm(component);
		}
		//$A.log(event);
	},
	buttonPress: function(component, event, helper) {
		helper.submitForm(component);
	}
})
FormHelper.js
({
	submitForm: function(component) {
		var firstName = component.find('firstName').get('v.value'),
			lastName = component.find('lastName').get('v.value'),
			toastEvent = $A.get("e.force:showToast");
	    toastEvent.setParams({
    		title: 'Welcome ',
    		message: firstName + ' ' + lastName + '!'
	    });
	    toastEvent.fire();
	}
})
This was selected as the best answer
yossi sud 6yossi sud 6
You can't wirte 
event.keyCode

you need to write 
event.getParams().keyCode
Raymond van Akkeren 8Raymond van Akkeren 8
Hello @KristofferGreene,

I thought of the same solution you described. Strangly enough I'm getting in the Helper method, but in the end somehow the Controllers doInit function is called again. Perhaps you dealt with this problem to.

Regards,

Raymond