Handle search input and clear events
by jorgeluis
HTML
<div id="app">
<p>
Handle both keyboard input and clear event on input type="search".
</p>
<p>
Add some text and either hit the enter key or clear the field (by clicking the X icon).
</p>
<br>
<label for="search">Search field:</label>
<input
id="search"
type="search"
@keyup.enter="handleEvent($event)"
@input="checkForClear($event)">
<div ref="events">
<h2>
Values:
</h2>
</div>
</div>
CSS
body {
padding: 20px;
font-family: sans-serif;
}
#app {
transition: all 0.2s;
}
h2 {
font-weight: bold;
margin-top: 2rem;
}
Vue
new Vue({
el: "#app",
data: {
},
methods: {
addEvent: function(text) {
var t = document.createTextNode(text);
var p = document.createElement('p');
p.appendChild(t);
this.$refs.events.appendChild(p);
},
handleEvent(e) {
if('' != e.target.value) {
this.addEvent(e.target.value);
e.target.value = '';
} else {
this.addEvent();
}
return;
},
checkForClear(e) {
if( undefined === e.data ) {
this.addEvent('--cleared--');
e.target.value = '';
}
return;
}
}
})