From d09968dbcbce57b02c4a86b2aa16c07586b332d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Tegn=C3=A9r?= Date: Wed, 6 Apr 2016 10:58:03 +0200 Subject: [PATCH] [changed] Prevent `Return` in menu from submitting surrounding form The default behaviour of hitting `Return` in a `` is to submit the immediate surrounding form. I would hazard a guess that this isn't the expected result when using `Return` to select an item in the autocomplete menu. Since we don't expose the event object to the consumer via `onSelect` we need to make sure we're making the most sensible choice by default. Hitting `Return` a second time (after the menu has closed itself) will result in the default, expected behaviour. --- lib/Autocomplete.js | 1 + lib/__tests__/Autocomplete-test.js | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/Autocomplete.js b/lib/Autocomplete.js index 65e02ddb..c6ab52b4 100644 --- a/lib/Autocomplete.js +++ b/lib/Autocomplete.js @@ -146,6 +146,7 @@ let Autocomplete = React.createClass({ } else { // text entered + menu item has been highlighted + enter is hit -> update value to that of selected menu item, close the menu + event.preventDefault() var item = this.getFilteredItems()[this.state.highlightedIndex] var value = this.props.getItemValue(item) this.setState({ diff --git a/lib/__tests__/Autocomplete-test.js b/lib/__tests__/Autocomplete-test.js index f35a04fd..f1c49ea7 100644 --- a/lib/__tests__/Autocomplete-test.js +++ b/lib/__tests__/Autocomplete-test.js @@ -211,6 +211,7 @@ describe('Autocomplete kewDown->Enter event handlers', () => { it('should invoke `onSelect` with the selected menu item and close the menu', () => { let value = 'Ar'; + let defaultPrevented = false; autocompleteWrapper.setState({'isOpen': true}); autocompleteInputWrapper.simulate('focus'); autocompleteWrapper.setProps({ value, onSelect(v) { value = v; } }); @@ -219,9 +220,10 @@ describe('Autocomplete kewDown->Enter event handlers', () => { autocompleteInputWrapper.simulate('keyUp', { key : 'r', keyCode: 82, which: 82 }); // Hit enter, updating state.value with the selected Autocomplete suggestion - autocompleteInputWrapper.simulate('keyDown', { key : 'Enter', keyCode: 13, which: 13 }); + autocompleteInputWrapper.simulate('keyDown', { key : 'Enter', keyCode: 13, which: 13, preventDefault() { defaultPrevented = true; } }); expect(value).to.equal('Arizona'); expect(autocompleteWrapper.state('isOpen')).to.be.false; + expect(defaultPrevented).to.be.true; });