Utilizing a variable beyond the confines of the script tag

Is there a way to assign the value of my variable place to my variable address, even though they are not in the same script tag? I want to bind the value and utilize it for fetching data. When I log my variable place, I can see the address, but I am unsure of how to set this value for my variable address.

<script>
let address = "";
</script>

They are **NOT** in the same script tag.

<div class="address">
                <label for="">Address: </label> <br />
                <script
                    src="https://maps.googleapis.fsdfsdfcom/maps/api/js?key=s&libraries=places"
                ></script>
                <input
                    id="autocomplete"
                    placeholder="address"
                    type="text"
                    bind:value={address}
                />
                <br />
                <script>
                    let autocomplete = new google.maps.places.Autocomplete(
                        document.getElementById("autocomplete"),
                        {
                            componentRestrictions: { country: "au" },
                        }
                    );

                    autocomplete.addListener("place_changed", () => {
                        var place = autocomplete.getPlace().formatted_address;
                    });
                </script>
            </div>

I need to retrieve the value of my variable place from the addListener function and use that value to update the address variable so I can fetch the necessary data. Despite trying various methods, I have been unsuccessful. I attempted using the global scope for the address variable without success.

I'm looking for a solution that allows me to use the value of place outside of the script tag to assign it to my address variable. This is within the context of SvelteKit.

Kind regards,

EDIT:

https://i.sstatic.net/rQTis.png

EDIT2:

https://i.sstatic.net/7zOlE.png

Answer №1

The variable place cannot be accessed because it is created within the addEventListener() method, limiting its scope to that specific function only. Any attempts to access place outside of this function will result in an error.

To resolve this issue, you can declare the place variable outside of the

addEventListener("place_changed", () => {});
and then assign it a value. By doing so, place will have global scope and can be accessed from anywhere in your code. Here's an example:

<script>
      let place; // Declare PLACE variable with global scope
      let autocomplete = new google.maps.places.Autocomplete(
          document.getElementById("autocomplete"),
          {
              componentRestrictions: { country: "au" },
          }
      );

      autocomplete.addListener("place_changed", () => {
        place = autocomplete.getPlace().formatted_address;
      });
</script>

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

Troubleshooting Java REST service integration in AngularJS for UPDATE and DELETE operations

After successfully implementing a REST service with Java and testing all HTTP methods using Postman, I decided to explore AngularJS. Upon integrating it to consume the REST service, I encountered issues specifically with the Delete and Put methods not func ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

Showing AngularJS information on Views

After successfully implementing static HTML with views, as shown in this example: https://embed.plnkr.co/MJYSP01mz5hMZHlNo2HC/ I am now facing a challenge with integrating the angular-ui accordion within ng-view. You can view the accordion I am attemptin ...

NuxtJS Static generated HTML page fails to load JavaScript while accessing /index.html

I'm currently working on a project using Nuxt.js to generate static content, which involves utilizing JavaScript for tasks such as navigation and form functionality. Everything works smoothly when running the page with npm run dev. However, after ex ...

In a VueJS project, access an xlsx file stored in the public directory by reading its contents

My current challenge involves trying to extract a quiz template from an xlsx file in order to create the quiz within it. Unfortunately, storing the xlsx file as json in a database is not a feasible solution for me at this time. I experimented with using ...

Node.js application experiences a crash upon entering incorrect credentials

Would you mind reviewing my Login Function? After entering incorrect credentials, a response is sent but unfortunately the app crashes The versions I am using are Express ^4.17.2 and Node.js v16.14.0 router.post( "/login", [ body(" ...

Can a snapshot be taken of an auto-generated ID document in FireStore?

Currently, I am working on developing both a mobile app and web app for my Final Year Project. As someone relatively new to Firestore, I am using a single instance of it to store data. When a customer registers through the mobile app, their information ge ...

How to optimize updating object properties with setState?

Is there a more efficient way to rewrite this code? For example, would using setState(ContentStore.getAll()) achieve the same outcome? I believe this approach appears overly cluttered and any method to simplify the code for readability would be greatly app ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

Tips for implementing a waiting period during an ajax request using jQuery

My current task involves calling a URL to generate a token and then opening another page on the same site once the token is generated. The issue I'm facing is that the window generating the token closes quickly, making it difficult for me to authentic ...

Is there a way to eliminate the surplus 2 download icons from this Angular code when there are a total of 3 users?

Here is some HTML code snippet: <tr *ngFor="let user of users"> <td> <h6 class="font-medium">{{user.id}}</h6> </td> <td> <h ...

Get the Label Values Based on CheckBox Status

Is there a way to retrieve the values of labels corresponding to checkboxes in HTML? I have multiple labels and checkboxes next to each other, and I want to be able to get the label values if the checkbox is checked. Can you provide guidance on how to do ...

Leveraging Ajax with PlayFramework Results

As stated in the PlayFramework Document 2.0 and PlayFramework Document 2.1, it is known that Play can return various responses such as: Ok() badRequest() created() status() forbidden() internalServerError() TODO However, when trying to send a response wi ...

Event not tracking properly due to missing label in GA event firing

Seeking assistance with a project I'm currently engaged in. I have created an HTML5 video containing a playlist and encountering difficulties setting up multiple labels in GA to track each individual video play. While I found code online, adapting it ...

extract data obtained from an AJAX call

I am working on an ajax request in my code: var rootURL = "http://localhost/myapp/api/api.php"; $.ajax({ type: 'GET', url: rootURL + '/favourites', dataType: "json", success: function(list) { }, error: f ...

Can we generate a JSON format that resembles the following structure?

Currently, I am in the process of transferring data from one system to another. The developer at the remote system has provided me with an example of a JSON structure that should be included in the body of the REST call. The structure is outlined below: ...

Use jQuery to parse the JSON below and then showcase the information in an HTML table

Can anyone assist me with parsing the following JSON using jQuery and presenting it in an HTML table? I want to showcase the values of "key" and "doc_count" in an HTML table. Your help would be greatly appreciated. Please find the JSON data below: { ...

Error: Unable to access property 'addEventListener' of null. This issue appears to be related to a Chrome extension

It's been frustrating dealing with this persistent error. I'm in the process of creating my very first chrome extension and for some reason, I just can't seem to pinpoint what's wrong with this particular code snippet: let beginButton = ...

How does a browser decide to load content from an http URL when the frontend source is using an https URL?

When using my Vue component to load external content in an iframe, everything works fine locally. However, once I deploy it to my HTTPS site, I encounter an issue. <iframe src="https://external-site" /> Upon deployment, I receive the following erro ...