Troubleshooting Issues with Form Inputs in JS/Angular Using Places API and document.getElementById Method

I have integrated the Google Places API to automatically populate locations/destinations into a form after a user searches. The auto-population works correctly, but I am facing an issue when trying to submit the form into my database – the object is always undefined. This problem arises specifically after the auto-population has taken place.

Interestingly, if I manually copy and paste the same information that was auto-populated into the text fields, the form submits successfully and the data gets inputted into my database without any issues.

Any thoughts on why this is happening? Shouldn't the values be bound to my ng-model when I attempt to submit the form, considering that I am auto-populating the correct values into the form?

HTML ========================

<div class="container-fluid">
    <div class="row">
        <div class="col-md-2">
            <h3>Markers</h3>
            <form ng-submit="addMarker(newMarker)">
                <div class="form-group">
                    <p>Add a new marker: </p>
                    <div class="form-group">
                        <input type="text" class="form-control" id="title" placeholder="Title" ng-model="newMarker.title">
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="address" placeholder="Address" ng-model="newMarker.address">
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="category" placeholder="Category" ng-model="newMarker.category">
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="url" placeholder="URL (optional)" ng-model="newMarker.url">
                    </div>
                    <div class="form-group">
                        <textarea type="textarea" class="form-control" id="description" placeholder="Message (optional)" ng-model="newMarker.description"></textarea>
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="list" placeholder="Add to a list (optional)" ng-model="newMarker.list">
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="latitude" placeholder="Latitude" disabled="true" ng-model="newMarker.latitude">
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="longitude" placeholder="Longitude" disabled="true" ng-model="newMarker.longitude">
                    </div>
                    <input type="submit" class="btn btn-primary">
                </div>
            </form>
        </div>
        <div class="col-md-10">
            <input id="pac-input" class="controls" type="text" placeholder="Search Box">
            <div id="map"></div>
        </div>
    </div>
</div>

JS ==========================

// Get the HTML input element for search for the autocomplete search box
var input = document.getElementById('pac-input');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

// Create the autocomplete object.
var autocomplete = new google.maps.places.Autocomplete(input);

// Event Listener for a Places API search
google.maps.event.addListener(autocomplete, 'place_changed', function(){
    var infoWindow = new google.maps.InfoWindow({map: map});
    var place = autocomplete.getPlace();
    var contentString = '<p><b>'+place.name+'</b></p>'+
                        '<p>'+place.formatted_address+'</p>';
    var pos = {
            lat: place.geometry.location.lat(),
            lng: place.geometry.location.lng()
        };
    fillInForm(place);
    map.setCenter(pos);
    infoWindow.setPosition(pos);
    infoWindow.setContent(contentString);
});

// Auto fill the form from the Places API search
var fillInForm = function(place) {
  // Get the place details from the autocomplete object.
    var lat = place.geometry.location.lat();
    var lng = place.geometry.location.lng();
    var markerForm = {
            title: place.name,
            address: place.formatted_address,
            coordinates: ""+lat+", "+lng+""
    };
    for (var key in markerForm) {
        document.getElementById(key).value = '';
        document.getElementById(key).disabled = false;
        var val = markerForm[key];
        document.getElementById(key).value = val;
    }
    $scope.markerForm = markerForm;
}

// CREATE NEW MARKER ===============================
$scope.addMarker = function() {
    markersFactory.addMarker($scope.newMarker, function(returnDataFromFactory){
        if(returnDataFromFactory.hasOwnProperty('errors')){
            $scope.newMarkerErrors = returnDataFromFactory.errors;
        } else {
            // console.log(returnDataFromFactory.data);
            $scope.newMarker = {};
        }
    })
}

EDIT: Added rest of the container. Previously only provided the form div. Added the pac-input and map div.

Answer №1

When updating form elements directly using the document.getElementById function:

for (var key in markerForm) {
    document.getElementById(key).value = '';
    document.getElementById(key).disabled = false;
    var val = markerForm[key];
    document.getElementById(key).value = val;
}

Angular does not automatically detect these changes.

The Angular approach for data binding involves replacing the fillInForm function with:

var fillInForm = function (place) {
    $scope.$apply(function(){
       $scope.newMarker.title =  place.name;
       $scope.newMarker.address = place.formatted_address;
       $scope.newMarker.latitude = place.geometry.location.lat();
       $scope.newMarker.longitude = place.geometry.location.lng();
        });  
    }

$apply is necessary here because the place_changed event is triggered outside of the Angular digest loop

View the demo: plunker

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

Utilizing Angular 5: Enhancing ngFor with a Pipe and a Click Event

Iterating through an array of objects using *ngFor, I apply various filters via pipes to manipulate the resulting list. One of these pipes relies on a user input from a search field. Upon clicking on one of the ngFor elements, the corresponding object is p ...

Real-time chat system using PHP for one-on-one inquiries with server-sent events (not a group chat)

I'm currently working on developing a live chat inquiry form for a website using HTML server-sent events. I'm utilizing this tutorial as a foundation Here is my plan based on the tutorial: On the client side, users are prompted to enter a use ...

Customizing the font color and size of the MUI DatePicker default textfield is not supported

I'm encountering an issue with the MUI DatePicker as I am unable to customize the font color and font size of the date. Below is my code: const DateSettings = () => { const [value, setValue] = React.useState<Date | null>(); const handleC ...

Angular filter is designed to search for elements that contain a specific value, rather than only those that are an exact match

I am currently trying to relate rules to fields using the 'filter' filter in Angular. You can see an example of this implementation here: http://plnkr.co/edit/dQiv5lRzhQNjXZ6pVdWO?p=preview The code I am using for this purpose is as follows: &l ...

Discovering the number of intervals running at any given time within the console - JavaScript

I'm having trouble determining if a setInterval() is active or has been cleared. I set up an interval and store it in a variable: interval = setInterval('rotate()',3000); When a specific element is clicked, I stop the interval, wait 10 sec ...

Every individual child component must be assigned a distinct key prop, even if they are pre-defined. - Utilizing REACT

My navigation bar routes are sourced from a JSON file structured like this: { "categorias": [ { "nombre": "Teacher absences", "componentes": [ { "type": "url", ...

Redux saga will halt all other effects if one fails during execution

Having some trouble with yield all in saga effect, I've included a snippet of my code below function* fetchData(item) { try { const data = yield call(request, url); yield put(fetchDataSuccess(data)); } catch (error) { yield put(fetchDa ...

Capture XMLHttpRequest request and manually send a 200 status response using vanilla JavaScript

After extensive research, I found conflicting information on this topic. I need to intercept an XMLHttpRequest and simulate a 200 status response from the backend using plain Javascript. This is specifically for testing purposes. So far, I have made pro ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

Is it possible to use D3 for DOM manipulation instead of jQuery?

After experimenting with d3 recently, I noticed some similarities with jquery. Is it feasible to substitute d3 for jquery in terms of general dom management? This isn't a comparison question per se, but I'd appreciate insights on when it might b ...

React display

I've been working on a personal project and wanted to include a lottery wheel. I came across the 'lottery-wheel' package on npm, but unfortunately, my attempts to install and render it were unsuccessful. To install the package, I used the f ...

Convert the color hex codes to JSON format without the use of quotation marks

Currently, I am populating a JavaScript array named "data" with values. This array contains two elements: value and color, formatted like this: var data = [{value:226,color:"#FFFFF"},{value:257,color:"#FFFFF"}]; The issue is that the color should be repr ...

The v-for loop seems to only update the last element instead of all of them, which is incorrect

How can I ensure that all 3 page links in the nav are displayed in 3 languages of user choice? Initially, the language change works fine on page load. However, after clicking on a language change link once, only the last link's language changes instea ...

Is the controller of a nested view in Angular UI router automatically considered a child of the parent view's controller?

My UI-Router setup includes a main view for products and two nested states below it. I want each nested view to have its own controller while also inheriting some basic information from the parent controller (productsCtrl). However, when attempting to acce ...

How can I transfer Gmail message using express rendering parameters?

Using passport-google-oauth for authentication and the node-gmail-api for fetching gmail, I aim to display gmail message after authentication. In order to achieve this, I have written the following code in routes.js: app.get('/profile', isLogged ...

How to sort Firebase real-time database by the child node with the highest number of

I am working on a database feature that allows users to 'like' comments on posts. Is there a way for me to sort the comments based on the number of likes they have? Although I am aware of using .orderByChild(), my issue lies in not having a sep ...

The attribute selector specifically targets the number 3, excluding numbers such as 13 or 23 from being selected

Within a form, there is a segment that displays groups of 4 weeks in each division. Take a look at the code snippet provided below <div class="form-check" data-weeknr="1,2,3,4"></div> <div class="form-check" dat ...

Is there a way to retrieve the original JSON string from a GWT JavaScriptObject?

Working with JSONP in my GWT application has presented some challenges. When the server sends a json string, I am able to retrieve it in the form of a JavaScriptObject on the client side. The issue arises when my json data contains complex structures, usi ...

Interactive sidebar scrolling feature linked with the main content area

I am working with a layout that uses flexboxes for structure. Both the fixed sidebar and main container have scroll functionality. However, I have encountered an issue where scrolling in the sidebar causes the scroll in the main container to activate whe ...

The form I created retrieves select options via an ajax call, but after saving, the post values are not displaying as expected

I have created a form with the following HTML code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Populate City Dropdown Using jQuery Ajax</title> <script type="text/javascript" src="h ...