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

Is setting cache: 'no-store' in a fetch request enough to mimic client-side rendering behavior in Next.js?

Currently, I am working with Next.js and utilizing the fetch method to retrieve data: const res = await fetch(`${process.env.url}/test`, { cache: 'no-store', }) My understanding is that specifying cache: 'no-store' will trigger a fre ...

Exploring the Power of NPM Modules in an Electron Renderer

Having trouble accessing lodash in an electron renderer. I'm a beginner with Electron and know that both the main process and renderer (local html file) have access to node. I can require something from node core like fs and it works fine, but when I ...

Tips for accessing JSON values in JavaScript

How can I extract values from a JSON object in JavaScript? Below is the code snippet I've tried: var obj={"0.5":0.009333, "0.21":0.048667,"0.31":0.070667}; var value =0.21; var p=0; for(i=0; i<= obj.length ;i++){ if(value== obj[i]) ...

Is there a way to transform vanilla JavaScript code into Vue.js code?

// Vanilla JS Code Conversion const app = new Vue({ el: '#app', methods: { // Logged out Events loginHelp: function() { this.$refs.forgotten.style.display = 'flex'; this.$refs.login.style.display = 'none&apo ...

Is there an issue with my RABL configuration file?

Rabl is responsible for generating the children nodes rather than the main object. In my Rails-Angularjs project, I am attempting to use RABL to create a JSON file. Despite reading the documentation and creating a Rabl file for the show action, it seems t ...

When attempting to import and utilize a component from a personalized React Component Library, it leads to an Invariant Violation error stating: "

Currently, I am in the process of developing a React UI Kit/Component Library for internal use in our product line. Progress has been smooth so far, with everything functioning well and displaying correctly on Storybook. However, when testing the library ...

Definition of Stencil Component Method

I'm encountering an issue while developing a stencil.js web component. The error I'm facing is: (index):28 Uncaught TypeError: comp.hideDataPanel is not a function at HTMLDocument. ((index):28) My goal is to integrate my stencil component i ...

Displaying information from four different arrays in a column using ng-repeat

There are 4 arrays filled with dynamic data that I want to display in a vertical table. Currently, my code looks like this: This is the snippet of my code: <table class="table table-striped"> <tbody> <tr > <td n ...

Enhancing Values Across a Timeframe Using JavaScript

Last time, I asked about my code. Here is what I have currently: var secs = 100; setInterval(function() { var $badge = $('#nhb_01'); $badge.text((parseFloat($badge.text())+0.01).toFixed(2)); }, secs); I want the counter to increase by ...

Is there a way to retrieve the Boolean value from an ng-show attribute without having to re-evaluate the expression?

I'm currently working on a project that involves displaying and hiding a lot of content dynamically using ng-show. Some of the expressions being evaluated are quite lengthy, like this... <div ng-show="some.object.with.nested.values && ...

Having difficulty launching a new window within an app built with Electron and Nexjs (Nextron)

Attempting to launch a (Nextjs-generated) page in a new window is causing an error message to appear: Uncaught ReferenceError: global is not defined Here is the full error: react-refresh.js?ts=1665849319975:10 Uncaught ReferenceError: global is not de ...

Adjust the width of every column across numerous instances of ag-grid on a single webpage

I am facing an issue with Ag-grid tables on my webpage. I have multiple instances of Ag-grid table in a single page, but when I resize the browser window, the columns do not automatically adjust to the width of the table. We are using only one Ag-grid in ...

Is there a way to show information exclusively on the selected card upon clicking?

[click here to see image 1] https://i.sstatic.net/cfvUT.png [click here to see image 2] https://i.sstatic.net/ISXAU.png Greetings, fellow beginners! Once again I find myself stuck on a coding problem. I have fetched various workout data and displayed t ...

Utilizing Restangular in a factory to interact with REST API in AngularJS

While I have a grasp on utilizing Restangular in a controller, my perception is that Restangular functions as an ORM with enhanced capabilities. An ORM should not be aware of the application's state; that responsibility lies with the controller. I b ...

The webpage loaded through ajax is not rendering correctly

One of the challenges I'm facing is getting a JavaScript script to load an HTML page into a specific div element on another HTML page: The page that's being loaded, startScreen.html, looks like this: <!DOCTYPE html> <html lang="en ...

Tips for accessing the value from an input field in an AngularJS application

Looking at my DOM structure below, <input class="k-textbox ng-pristine ng-untouched ng-valid ng-valid-required" type="text" placeholder="" ng-blur="controller.isDirty=true" ng-change="controller.isDirty=true" ng-model="controller.model.value" ng-requir ...

Is it possible to notify the user directly from the route or middleware?

In my current setup, I am utilizing a route to verify the validity of a token. If the token is invalid, I redirect the user to the login page. I am considering two options for notifying users when they are being logged out: either through an alert message ...

NextJS for Self-hosting Fonts

I'm facing difficulties with self-hosting webfonts in my NextJS application. The browser is trying to access the fonts using this URL: localhost:3000/_next/static/css/fonts/Avenir.woff2 However, the actual path for these fonts is: _project_dir/static ...

Sending HTML content to viewChild in Angular 5

I'm struggling to figure out how to pass HTML to a ViewChild in order for it to be added to its own component's HTML. I've been searching for a solution with no luck so far. As a newcomer to Angular, many of the explanations I find online ar ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...