I'm trying to disable a form submission when the enter key is pressed. The approaches I've tried are listed below with the code and example demo.
Desired outcome: Focus on the input, press down -> down -> enter and it should log the index of the record you have selected and stop there.
What's actually happening: It logs as expected, but then reloads the page immediately as the form submits.
HTML
<form action="/some-action" @submit.stop.prevent="prevent">
<div class="auto-complete" v-cloak>
<div class="ico-input">
<input type="text" name="search" placeholder="Enter text" @keyup.prevent="handleKeypress">
</div>
<ul class="raw auto-complete-results">
<li v-for="r in results" @click="loadSelection($index)" v-bind:class="{'selected': selectedIndex == $index}"><span>{{ r.name }}</span></li>
</ul>
</div>
</form>
JS
var autocomplete = new Vue({
el: '.auto-complete',
data: {
results: [{name: 'swimming1'}, {name: 'swimming2'}, {name: 'swimming3'}, {name: 'swimming4'}, {name: 'swimming5'}, ],
selectedIndex: -1,
},
methods: {
handleKeypress: function(event) {
event.preventDefault();
event.stopPropagation();
var key = event.which;
if ([38, 40].indexOf(key) > -1) //handle up down arrows.
this.arrowNavigation(key);
else if (key == 13) //handle enter keypress
this.loadSelection(this.selectedIndex);
return false;
},
arrowNavigation: function(key, target) {
if (key == 38) //up
this.selectedIndex = this.selectedIndex - 1 < 0 ? 0 : this.selectedIndex - 1;
if (key == 40) //down
this.selectedIndex = (this.selectedIndex + 1) > (this.results.length - 1) ? 0 : this.selectedIndex + 1;
},
loadSelection: function(index) {
if (index < 0 || index > this.results.length)
return false;
var selection = this.results[index];
console.log("loading selection", index,selection);
},
prevent: function(event) {
event.preventDefault();
event.stopPropagation();
return false;
},
}
})
I've tried various syntax approaches on both form/input (switching submit
for keyup
on the input)
- v-on:submit="prevent"
- @submit
- @submit.stop
- @submit.prevent
- @submit.stop.prevent="prevent"
I've also tried calling the following from with in the 2 event handlers aswell as returning false from them both.
- event.preventDefault()
- event.stopPropagation()
The form still triggers a page reload no matter what I try. I can't see anything obviously wrong so I turn to stackoverflow to guide my eyes.
Thanks