Display alert only when focus is lost (on blur) and a dropdown selection was not made

Utilizing Google Maps Places for autocompletion of my input, I am aiming to nudge the user towards selecting an address from the provided dropdowns in order to work with the chosen place.

A challenge arises when considering enabling users to input addresses that may not be recognized by Google. Therefore, upon blur, an alert is meant to prompt the user to confirm if the entered address is accurate.

The dilemma lies in the fact that even after selecting an address from the dropdown, the alert still appears due to the input blurring out.

Is there a way to ensure that the alert only displays when no Google-suggested place was selected and the input actually blurs?

<template>
    <input
           type="text"
           name="address"
           @blur="onBlur()"
    />
</template>

<script>
//...
mounted: function() {
    this.autocomplete = new google.maps.places.Autocomplete(
        document.getElementById(this.id),
        this.options
    );

    this.autocomplete.addListener('place_changed', (blur) => {
        console.log('place changed ');
        let place = this.autocomplete.getPlace();
        this.setAddress(place);
    });
},

methods: {
    onBlur() {
        this.isThisYourAddress();
    },

    isThisYourAddress() {
        return swal('test');
    }
}
</script>

Answer №1

A clever approach is to utilize $refs to store the input value each time it changes. When the input loses focus, compare the current value with the last saved value. To ensure data integrity during this process, a brief delay is introduced before performing the comparison. A more efficient method for managing this transition could be implemented.

new Vue({
  el: '#app',
  data: {
    lastSelected: ''
  },
  mounted() {
    this.autocomplete = new google.maps.places.Autocomplete(
        document.getElementById('auto'),
        this.options
    );

    this.autocomplete.addListener('place_changed', (blur) => {
        var  place = this.autocomplete.getPlace();
        this.lastSelected = this.$refs.input.value;
        console.log('place changed ', this.lastSelected);
        this.setAddress(place);
    });
  },
  methods: {
      onBlur() {
        setTimeout(() => {
          const v = this.$refs.input.value;
          if (v !== this.lastSelected) {
            this.lastSelected = v;
            this.isThisYourAddress();
          }
        }, 100);
      },

      isThisYourAddress() {
        return 'something'
      }
  }
})

https://codepen.io/anon/pen/WXVRaY?editors=1111

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

What is preventing my CSS variables from functioning in my Vue component that is utilizing SASS?

Currently, I am working with sass and vue version-3. Within one of my components, the following code is present: HelloWorld.vue : <template> <div class="greetings"> <h1>{{ msg }}</h1> <h3> You’ve succe ...

Incorporate a new JavaScript animation as the background for an established website, replacing the static background image

Seeking assistance with my portfolio as I delve into the world of Webdesign and learn the basics from templates. How can I integrate this javascript code into the background of my site, replacing the current minecraft image? Every attempt to implement it ...

How to Insert PHP/MySql Data into JavaScript

As I delve deeper into PHP OOP, I feel like I'm making progress in transitioning my website. Currently, each user has their own page with a javascript grid tailored to their specific needs. For easier maintenance, I'm considering the idea of havi ...

Determine the elapsed time in seconds between two specified moments

I am trying to implement two input fields in my HTML, one for a starting point and another for an end point. The user will enter two times like this: For example: [8:15] - [14:30] alert("XXXXX seconds") I want to calculate the number of seconds between 8 ...

Error message appearing repeatedly and submit button functioning only after second click

I am currently working on my CS50 Final Project, where I am in the process of designing a web app using Flask. Specifically, this issue arises in the login/register page where I am attempting to verify if the username is already taken (through jsonify) and ...

What is the best way to transfer the value of one directive attribute to another directive in AngularJS?

For instance: <custom-main> <custom-sub1 att-name="test"></custom-sub1> <custom-sub2></custom-sub2> </custom-main> JavaScript Source Code bosAppModule.directive('custom-main',[&apos ...

Issue in Jquery: Unable to load the corresponding pages when toggling the checkbox on and off

I am facing an issue with a checkbox and calling different php pages based on the status of the checkbox. Currently, the code works only for checked checkboxes. I'm not sure why it's not working for unchecked checkboxes as well. <script type ...

Ways to modify, delete, or insert data elements within a collection of values using React

I'm currently working on implementing a dropdown menu for departments within a location edit form. I'm wondering if there's a way to update or create new elements in the list of values. The API I'm using only sends specific data elemen ...

Vue.js - Launching Modal for Editing Data Entry

I have a list of records with corresponding buttons on the right side, as shown in this image: Whenever I click on one of these buttons, I want a dialog box to appear containing various input fields such as text inputs, dropdowns, and checkboxes. This dia ...

What is the most effective way to retrieve cursors from individual entities in a Google Cloud Datastore query?

I am currently working on integrating Google Cloud Datastore into my NodeJS application. One issue I have encountered is that when making a query, only the end cursor is returned by default, rather than the cursor for each entity in the response. For insta ...

Adjust the text appearance of the graph in ApexCharts

Is there a way to adjust the font size of the donut chart generated by using apexchart? You can view the image here. <template> <section> <v-card raised> <v-card-title class="blue--text">Requests Overview</v-card-ti ...

Transferring an array to PHP using AJAX

In this coding scenario, I initialize my array: let myArray = []; Within a loop, elements are added to the array as follows: myArray.push($(this).data('id')); // Example: [1, 2, 3, 4] Subsequently, I transmit this data to PHP using AJAX throu ...

Can all actions in the ofType operator be waited for before calling next?

I have a list of dynamic redux actions that I need to monitor in order to trigger another action in my epic once all of them have been called. The key here is that the actions within this list can change and are not fixed. It would be ideal if the ofType o ...

The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'? Cannot set property 'two' of unde ...

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 ...

Ways to verify whether any of the variables exceed 0

Is there a more concise way in Typescript to check if any of the variables are greater than 0? How can I refactor the code below for elegance and brevity? checkIfNonZero():boolean{ const a=0; const b=1; const c=0; const d=0; // Instead of ma ...

Make sure a div is displayed on top of any content currently in fullscreen mode

I recently encountered an issue with my Chrome extension where a menu I inserted into the page would disappear whenever a flash or html5 video player went full screen. Is it possible to have two objects in full screen simultaneously, or is there another so ...

How come my Ajax call is setting the 'Content-Type' to 'application/x-www-form-urlencoded' instead of 'JSON' as specified in the dataType parameter?

I have encountered an issue while responding to a button click using the code snippet below. The console.log() confirms that the function is being called, but the HTTP request it generates contains the header "Content-Type: application/x-www-form-urlencode ...

Create a placeholder for the module function

Update: Providing more specific details. Our team has developed a Github API wrapper extension and we are looking to test different use cases for it. However, we prefer not to use the API wrapper extension directly during testing and instead want to stub ...

What is the best approach in VueJS to implement a skeleton loader and an empty page condition for my orders page simultaneously?

I have implemented a skeleton loader to display while the data is loading. However, I want to also show an empty order page if there is no data or orders coming in. I am trying to figure out the conditions for both scenarios - displaying the loader and t ...