Aidiakapi
Aidiakapi

Reputation: 6249

Form enter key action with lists and AngularJS

In my AngularJS project I have an account details page where you can change your personal account information. This page allows for multiple phone numbers and e-mailaddresses to be supplied. Using mouse input (or tabbing to buttons and pressing them with space bar) works perfectly, however I'd like to add the convenience of the enter key pressing the 'logical' buttons.

My form looks like (accidentally forgot to translate a few items): Form overview

A simplified version of the HTML for the form can be found on PasteBin, I've mainly removed the directives for managing the lists.

All buttons are <button> elements except for the cancel button which an <a> to the previous page, and the submit button is <button type="submit">.

When selecting any text box and pressing enter, the first (non-disabled) <button> element is 'clicked'. Meaning if I would change the last name, hit enter, the first phone number would be removed.

When you're in a new entry of phone numbers or e-mailaddresses (the row with the green + button) it should click that button, and if it's disabled do nothing. When you're in any other text box on the form it should hit the save button, and also if the save button's disabled, do nothing.

Both buttons will be disabled based on form validation.

There'd be no trouble in changing the type of a button from button to submit if that'd help.

I would preferably have an all HTML solution, using just semantics, but I doubt that's really possible. So the logical alternative would be to use an AngularJS directive.

Please do not provide a jQuery or plain JavaScript solution relying on IDs or something like that. I don't want to hack my way around AngularJS, rather embrace it.

Upvotes: 0

Views: 1071

Answers (2)

Michael Vashchinsky
Michael Vashchinsky

Reputation: 2137

I just tried to replace

<button>Cancel</button>

with

<input type="button" value="Cancel"> 

and it seems to work correctly...

Upvotes: 0

Aidiakapi
Aidiakapi

Reputation: 6249

In the meantime I've worked on a directive that allows me to declare what I've called 'submit scopes'.

In essence you have actions (inputs) and targets (buttons), they're bound through a service by a key you can assign in the template. To avoid keys from clashing and from simple annoying work you can create a submit-scope which will cause it's children to prepend a unique key to the value they're accessing.

Within a submit-scope you can still override an action to use a global key instead by setting the attribute global-submit="true".

Example code:

<div submit-scope>
     <input type="text" submit-action />
     <button type="button" submit-target>Pressing enter in the above field will click this button.</button>
</div>

You can view the entire source code and a slightly larger example on Plnkr.

Upvotes: 0

Related Questions