tips for dynamically highlighting search bar after choosing a different dropdown option - vuejs

I need to filter products in my application based on name and category. To achieve this, I have included a search text box and a dropdown select box. The dropdown select box offers two options: 1. Search products by name 2. Search products by category name. Depending on the selected option, the search text box will be activated and focused.

Here is the template code:

<el-form>
      <el-row :gutter="15"
              type="flex"
              class="search__product">
        <el-col class="filter_option">
            <app-select name="ProductFilter"
                        :options="filterOptions"
                        :selected="selectedSearchOption"
                        @onChange="onSearchOptionChange" />
        </el-col><el-col class="search_input">
            <el-input placeholder="Search product"
                      aria-label="Search product"
                      @keyup.enter.native="searchProduct"
                      v-model="filterText">
            </el-input>
        </el-col>
      </el-row>
    </el-form>

Function to populate dropdown values:

    get filterOptions(): OptionTypes[] {
    return [
      { label: 'Search by Product Name', value: 'Product' },
      { label: 'Search by Category Name', value: 'Category' }
    ]
  }

Function for searching products:

searchProduct() {
    if (this.filterText !== '') {
      this.$store.dispatch('fetchProductsBySearchName', this.filterText)
    }
  }

Event for dropdown selection change:

    onSearchOptionChange(value) {
    this.selectedSearchOption = value
  }

The current setup works well for searching products by name. I now intend to enhance the functionality by enabling and focusing the search text box based on the dropdown selection.

Answer №1

Note that this answer pertains specifically to the el-input component in the Element-ui library:

Your select statement will remain unchanged:

<app-select name="ProductFilter"
            :options="filterOptions"
            :selected="selectedSearchOption"
            @onChange="onSearchOptionChange" />

Regarding the reference for the el-input component:

<el-input ref="myInput"
          placeholder="Search product"
          @keyup.enter.native="searchProduct"
          v-model="filterText">

Within your method:

onSearchOptionChange(value) {
  this.selectedSearchOption = value

  // There are several ways to achieve this task (selecting the `input` element)
  // You can use any of the lines mentioned below ;)
  this.$refs.myInput.$el.firstElementChild.focus();
  this.$refs.myInput.$el.lastElementChild.focus();
  this.$refs.myInput.$el.children[0].focus();

  this.$refs.myInput.$el.querySelector('input').focus(); // Personally preferred for future compatibility 
}

UPDATE

As suggested by @charlie, you may need to place the code inside a this.$nextTick function:

onSearchOptionChange(value) {
  this.selectedSearchOption = value

  this.$nextTick(() => { 
    // There are multiple methods to achieve this task (selecting the `input` element)
    // You can use any of the lines mentioned below ;)
    this.$refs.myInput.$el.firstElementChild.focus();
    this.$refs.myInput.$el.lastElementChild.focus();
    this.$refs.myInput.$el.children[0].focus();

    this.$refs.myInput.$el.querySelector('input').focus(); // Personally preferred for future compatibility 
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can an infowindow be automatically closed based on specific criteria?

Show the infowindow only when hovering over the marker. It should disappear when moving the mouse away from the marker. The infowindow should stay open only if you click on the marker, and can be closed by clicking the close button on the infowindow. ...

What is the best way to dynamically pass JSON object values to PHP?

Greetings, I am new to JSON and Ajax. Although my question may seem trivial, I believe that even the simplest inquiries are crucial in the learning process. My dilemma involves passing two parameters (giorno and periodo) via Ajax: For example: 'gior ...

The sharpness of images may diminish when they are created on an HTML5 Canvas within Next JS

I am currently working on a project where users can upload an image onto an HTML5 canvas with fixed dimensions. The uploaded image can be dragged and resized using mouse input while preserving its aspect ratio. Below is the draw function I am using to achi ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

When attempting to pass react-intl as an argument in a method of a React component during Jest testing, an error is thrown stating, "TypeError: intl.formatMessage is not a function."

Currently, I am in the process of unit testing my React component using Jest. Within this component, there are several methods that are called upon. As an example: export function fetchText(text, intl) => ((text !== 'NA') ? (intl.formatM ...

Is there a particular Javascript event triggered when the user clicks on the Stop loading button?

When the user clicks the 'Stop Load' button (red X in most browsers) or presses the Esc key on the keyboard, I need to execute some Javascript code. I've seen solutions for capturing the Esc key press by using document.body.onkeyup, but I ha ...

Tips on successfully transferring row data that has been clicked or selected from one adjacent table to another table

Currently, I am facing a challenge with two tables that are positioned next to each other. My goal is to append a selected row from the first table to the second table. After successfully extracting data from the selected row and converting it into an arr ...

Is there a way to efficiently line up and run several promises simultaneously while using just one callback function?

I am currently utilizing the http request library called got. This package makes handling asynchronous http connections fast and easy. However, I have encountered a challenge with got being a promisified package, which presents certain difficulties for me ...

Looking to empty a textbox, give it focus, and avoid triggering an ASP.NET postback all with a single click of a

I am working on an ASP.NET project and I have a simple HTML button. When this button is clicked, my goal is to clear textbox1, set the focus on textbox1, and prevent any postback from occurring. However, I am running into an issue where preventing postba ...

In Angular's production build on Webkit/Safari, the left-hand side of the operator '=' must be a reference

Recently, I completed a project using Angular. After successfully building it for production without any errors, everything seemed to work perfectly on Chrome. However, when attempting to run the app on Webkit/Safari, an error was displayed in the cons ...

Cease the audio from playing unless you are actively hovering over the image

Is there a way to make the sound stop playing when you are not actively hovering over the picture? Any suggestions on how to achieve this would be greatly appreciated! imgarr[i].onmouseout=function(){ this.setAttribute('src',this.getAttribu ...

When Infinite Scroll is integrated into another file with HTML tags stacked on top, it will not load additional posts when scrolling down

I have implemented an Infinite Scroll feature that dynamically loads more data from a database as users scroll to the bottom of the page. However, I encountered an issue when trying to include this functionality in another .PHP file. If I insert any HTML ...

Instruction on inserting NativeBase footer into my React Native application?

As someone new to React Native, I am trying to include a footer bar in my app. Below is the code snippet from my dashboard.js file where I attempted to add the footer bar, but it doesn't seem to be working as expected: import React, { memo } from &ap ...

Loading STL files from a buffer instead of a path within Three.js

I'm struggling to showcase a user-uploaded STL file in Three.js. The issue arises when my file is delivered to the front-end through a GET request: res.sendFile(path). Unfortunately, I can't directly utilize this raw data to load the file withou ...

Dynamic mouse path

Currently, I am in the process of creating a mouse trail similar to what is found on this particular website. I have been using JavaScript, jQuery, and various libraries in my attempt to achieve this effect; however, it has proven to be more challenging th ...

Set the background color of the Material UI Drawer component

Need some advice on changing the background color of Material UI's Drawer. I've attempted the following approach, but it's not producing the desired result. <Drawer style={customStyle} open={this.state.menuOpened} docked={false} ...

Formatting numbers in Angular 2 to include a space every three zeros in a money amount

Let's say I have the number 30000 and I want to format it as 30 000. What method should I use to achieve this? Here are more examples: 300000 -> 300 000, 3000000 -> 3 000 000. Just to clarify, this is not about using dots or commas, but rathe ...

Dealing with undefined properties in Javascript can cause errors

[ { dateTime: '2016-03-30 05:55:53', value: '4.0' }, { dateTime: '2016-03-30 05:55:55', value: '17.0' }, { dateTime: '2016-03-30 05:55:57', value: '17.0' }, { dateTime: '2016-03-30 06:0 ...

Troubleshooting Vue.js rendering problems on Safari_BROWSER

I'm encountering a strange issue with my portfolio website, which is built using Vue and Laravel. The problem arises specifically in Safari - the project thumbnails don't display until the browser window is resized. Here's the relevant code ...

Aligning a DIV using javascript

Hey everyone, I'm encountering an issue with the JavaScript on my website. I'm struggling to center the div in order to properly display the image I click on. It seems to work fine on the second attempt, but on initial click, the div always appea ...