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 distinguishes {key:" "} from {key:" "}, when it comes to JSON files?

I have been working on implementing validation using express Router. The issue I encountered is that when I pass {title:""}, the express-validator does not throw an error. However, when I pass {title:" "}, it works properly. exports.postValidatorCheck = [ ...

Moving DOM Elements around

Objective: Looking to relocate an element within the DOM structure. Condition: Although I am familiar with using jQuery for this task, I am currently working in an environment without access to it. Therefore, I need a pure JavaScript solution. Example: ...

Trouble with Angular 1.6 ng-repeat not showing search results

I can't seem to figure out why ng-repeat is not showing the search results. Here's what works: Using an HTTP GET request to retrieve all data from the database, and seeing the results displayed by ng-repeat. Sending an HTTP GET request with ...

Convert data in JavaScript and send it as a string in PHP

I'm currently facing a small issue with my JavaScript code. Specifically, I am using AJAX and attempting to retrieve a variable in PHP. Everything seems to be working fine except for the "param" data. Below is the snippet of my code: $('#sign ...

An alternative method for storing data in HTML that is more effective than using hidden fields

I'm trying to figure out if there's a more efficient method for storing data within HTML content. Currently, I have some values stored in my HTML file using hidden fields that are generated by code behind. HTML: <input type="hidden" id="hid1 ...

What could be causing me to receive null when trying to retrieve an element with document.getElementById, even after invoking $(document).ready(function() { ... })?

Here's a small example. I'm feeling a bit rusty with JavaScript, as it's been some time since I last worked with it. The problem I'm encountering is an error in Chrome developer tools: "Uncaught TypeError: Cannot set property 'src ...

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

Experiencing difficulties in transmitting multipart form data from React to Express Js accurately

I am facing an issue with uploading files using Dropzone and sending them to a Java backend API from React JS. In this scenario, React sends the document to Express backend where some keys are added before forwarding the final form data to the Java endpoin ...

Incorporating arguments within the context of a "for each" loop

I'm attempting to develop a straightforward script that converts RGB-16 colors to RGB-8. The script is functioning properly, but I'm having trouble converting it into a function that can handle two different palettes. Whenever I try using palette ...

Tips for managing the onloadedmetadata event

If a video file cannot be played by the browser due to format or codec issues, I want to notify the user about it. When the browser is unable to play a video (because of unsupported format or codec), the onloadedmetadata event does not occur. I have some ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

Unlock real-time alerts with the power of JavaScript and PHP!

I am currently working on enhancing my skills in javascript. I have a basic idea of what I want to achieve. My goal is to create an automated javascript function that accesses a php page. This php page will create an array of new notifications for the ja ...

"Step-by-step guide on uploading multiple images to a Node server and storing them in

Hey everyone! I'm currently working on a project using React and MongoDB. Users are required to register and login before accessing the app. Once logged in, they can input their name, number, and images through a form. However, I've encountered a ...

Input a new value into the registration field to update it

My current task involves adding a new text field to a React form using a button. I need this new input text field to be able to store data on a register. How can I go about setting this property? Typically, when creating a text field, you would utilize co ...

What is the process for including a field specific to a date in a form?

I need the user to select a month and year. In one column, there will be the days of the month they selected [e.g. 1-30]. Users can then add habits in other columns. I want users to be able to input an 'X' for each habit row on a specific date [e ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...

The JavaScript program for the shopping list is experiencing issues with the formatting of list items

I have been working on developing a shopping list program using JavaScript. The program includes an input box and an "add item" button, which adds the text entered in the input field to an unordered list as a list item. Each list item also contains an imag ...

waiting for udp response in node.js using express

Currently, I am diving into the world of node.js programming and have encountered a challenge. While working with express, I came across an issue. When a POST request is made, it triggers a radius authentication process over UDP using the dgram module. Ho ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

Employing the power of JavaScript to enable the seamless toggle of an overlay

I have a div named "navbar_menu". On clicking this div, I want the visibility of the div named "nav_overlay" to fade in. Upon another click, I want it to fade back and become invisible again. Currently, I have set the div 'nav_overlay" to have ' ...