Eric Guan
Eric Guan

Reputation: 15992

Set input value that has been binded with v-model

I'm creating my own autocomplete feature based on vue.js and materializecss.

https://jsfiddle.net/guanzo/kykubquh/5/

Right now it's working okay, except for a few things.

The normal behavior for an autocomplete is that once you select an item by pressing enter, or clicking, the value of the input becomes your selected item. So if you input "alab", and select the item "Alabama", the value of the input should become "Alabama", and the dropdown list disappears.

The problem is that the input is bound with v-model="query", meaning the value of the input is the value of "query", which is the value of the input.

Trying to change the input value with this.$el.querySelector('input').value = "Alabama" does nothing. My current workaround is to set the value of query to be the value of the selected state.

onSelect(state){
    this.selected = state;
    this.query = state.name//replace input val
}

A nasty side effect of this is that changing the value of query triggers another search, which causes the dropdown to reappear with the item "Alabama".

How do i change the value of an input that has been bound with v-model?

My attempted workaround is to call this.onBlurInput(); after the user selects an item, which hides the dropdown. However, the dropdown will no longer appear until you explicity refocus the input by clicking outside and back again.

Upvotes: 1

Views: 746

Answers (1)

Bert
Bert

Reputation: 82439

Remove your focus and blur events and add the following line to your queryMatches. You really only want to show options when there is not an exact match.

queryMatches(){
    if(this.query.length <= 1){
        return [];
    }

    // check to see if the current value is already in the list
    if (this.query === this.selected.name) return [];

    console.log(this.query)
    var reg = new RegExp(this.query,'gi')
    var matches = this.states.filter(state=>{
        return reg.test(state.name)
    })
    console.log(matches)
    return matches
}

Here is an updated fiddle.

Upvotes: 1

Related Questions