Retrieving data from the <script> tag and transferring it to the t-esc tag within Odoo 12

After attempting to retrieve the current coordinates of a location in Odoo, I successfully obtained longitude and latitude data through an alert generated by the following code:

<button onclick="getLocation()">Try It</button>

                            <p id="demo"></p>

                            <script>
                                var x = document.getElementById("demo");

                                function getLocation() {
                                if (navigator.geolocation) {
                                navigator.geolocation.getCurrentPosition(showPosition);
                                } else {
                                x.innerHTML = "Geolocation is not supported by this browser.";
                                }
                                }
                                function showPosition(position) {
                                x.innerHTML = "Latitude: " + position.coords.latitude +
                                "Longitude: " + position.coords.longitude;
                                }
                            </script>

Now, the challenge lies in populating my Odoo fields `gps_coordinates_latitude` and `gps_coordinates_longitude` with these extracted coordinates. The template file in Odoo looks like this:

<template id="create_case" name="Create Case">
    <t t-call="website.layout">
        <div class="container">
            <script>
                var x = document.getElementById("demo");

                function getLocation() {
                if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
                } else {
                x.innerHTML = "Geolocation is not supported by this browser.";
                }
                }

                function showPosition(position) {
                var lati = position.coords.latitude; <t t-esc="gps_coordinates_latitude"/>
                alert(position.coords.longitude);
                x.innerHTML = "Latitude: " + position.coords.latitude +
                "Longitude: " + position.coords.longitude;
                alert(position.coords.latitude);
                }
            </script>

            <h1 class="text-center mt16 mb16">Create Case</h1>
            <p>Click the button to get your coordinates.</p>
            <button onclick="getLocation()">Try It</button>
            <p id="demo"></p>
            <form action="/mycase/process" method="POST" class="form-horizontal mt32" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
                <div t-attf-class="form-group #{error and 'case_title' in error and 'has-error' or ''}">
                    <label class="control-label" for="case_title">Case Title</label>
                    <input type="text" class="form-control" name="case_title" required="True"
                           t-attf-value="#{case_title or ''}"/>
                </div>
                <div t-attf-class="form-group #{error and 'case_description' in error and 'has-error' or ''}">
                    <label class="control-label" for="case_description">Case Description</label>
                    <input type="text" class="form-control" name="case_description" required="True"
                           t-attf-value="#{case_description or ''}"/>
                </div>
                <div t-attf-class="form-group #{error and 'case_type' in error and 'has-error' or ''}">
                    <label class="control-label" for="case_type">Case Type</label>
                    <select class="form-control" id="case_type" name="case_type" required="True">
                        <t t-foreach="case_type" t-as="case_type">
                            <option t-attf-value="#{case_type.id}">
                                <t t-esc="case_type.name"/>
                            </option>
                        </t>
                    </select>
                </div>
                <div t-attf-class="form-group #{error and 'project' in error and 'has-error' or ''}">
                    <label class="control-label" for="project_name">Projects</label>
                    <select class="form-control" name="project_name" required="True">
                        <t t-foreach="projects" t-as="project">
                            <option t-attf-value="#{project.id}">
                                <t t-esc="project.name"/>
                            </option>
                        </t>
                    </select>
                </div>

                <div>
                    <label class="control-label" for="gps_coordinates_latitude">Latitude</label>
                    <input type="text" class="form-control" name="gps_coordinates_latitude"
                           t-attf-value="#{gps_coordinates_latitude or ''}"/>
                </div>

                <div t-attf-class="form-group #{error and 'case_description' in error and 'has-error' or ''}">
                    <label class="control-label" for="gps_coordinates_longitude">Longitude</label>
                    <input type="text" class="form-control" name="gps_coordinates_longitude" required="True"
                           t-attf-value="#{gps_coordinates_longitude or ''}"/>
                </div>

                <div t-attf-class="form-group #{error and 'ratings' in error and 'has-error' or ''}">
                    <label class="col-form-label" for="ratings">Ratings</label>
                    <select class="form-control o_website_form_input" name="ratings" required="false"
                            widget="priority">
                        <option value="normal">Normal</option>
                        <option value="good">Good</option>
                        <option value="very_good">Very Good</option>
                        <option value="excellent">Excellent</option>
                    </select>
                </div>
                <div t-attf-class="form-group #{error and 'attachment' in error and 'has-error' or ''}">
                    <label class="col-form-label" for="attachment">Attachments</label>
                    <input id='attachment' type="file" class="form-control o_website_form_input"
                           name="attachment" multiple="true" data-show-preview="true"/>
                </div>
                <div class="form-group">
                    <button class="btn btn-primary btn-lg">Submit Case</button>
                </div>
                <div class="oe_chatter">
                    <field name="message_follower_ids" widget="mail_followers"/>
                    <field name="message_ids" widget="mail_thread"/>
                </div>
            </form>
        </div>
    </t>
</template>

Answer №1

Instead of using t t-esc, you can directly retrieve the value in JavaScript.

Make changes to your JavaScript code and set the values for your input fields gps_coordinates_latitude and gps_coordinates_longitude, like this:

document.getElementsByName("gps_coordinates_latitude")[0].value = position.coords.latitude;
document.getElementsByName("gps_coordinates_longitude")[0].value = position.coords.longitude;

I hope this solution resolves your issue.

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

Retrieving and submitting text in a NodeJS environment

I'm attempting to retrieve text from an API that only provides a string of text ((here)), but I am encountering difficulties in displaying it accurately. When I try to post it, the output shows as [object Response], and the console.log is not showing ...

Using jQuery to change date format from mm/dd/yy to yyyy-dd-mm

I need to transform a date in mm/dd/yy format from an ajax response into yyyy-mm-dd format using jquery. Is there a built-in function in jquery that can handle this conversion for me? ...

Why is the state object empty in this React Native function?

One React-Native component I have is responsible for rendering an image gallery in a list format. This component is called once for each item on the parent list. It takes two props: "etiqueta," which contains the title of the item, and "galleries," which i ...

Experimenting with the speechSynthesis API within an iOS webview application

I'm currently working on developing an app that features TTS capabilities. Within my webview app (utilizing a React frontend compiled with Cordova, but considering transitioning to React Native), I am implementing the speechSynthesis API. It function ...

Angular does not assign the ng-invalid-class to the input

In order to register custom validation methods for custom form elements, we use extra directives as shown below: <ng-form name="validatorTestForm"> <our-input-directive name="validatorTest" ng-model="ourModel"/> ...

Transmitted only JSON data instead of using multiform data with jQuery Ajax

When I use jQuery Ajax to send a JSON object, it ends up being interpreted as 'multiform' instead of pure JSON. How can I make sure my request is sent as a pure JSON object and not multiform? var demo = new Array("One", "Two", "Three"); $.ajax ...

The jQuery code functions smoothly on computers, but experiences delays when running on an iPhone

I was working on my website and trying to add a div that sticks to the top of the browser when it scrolls out of view. I found a script that works well on desktop, but when testing it on iPhone, there is a slight delay before the div pops back up in the ri ...

Clearing form data after submitting in Laravel using axiosIn Laravel, utilizing

When working on my Laravel app, I encountered an issue while submitting a form using Vue and Axios. Despite my attempts to clear the input field after submission, it doesn't seem to work. HTML: <form method="post" enctype="multipart/form-data" v- ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

Converting HTML to a Text String (not for display) using Angular

When it comes to displaying HTML in Angular, there are numerous approaches available. For example, using $sce.trustAsHtml(myHtmlVariable) is one way to achieve this. However, I am interested in creating something like the following: myStringVariable = s ...

"Manipulate the contents of a state array by adding or removing items at specific indices in React, alongside other array

I am facing a challenge in removing items from an array that have been added to a state array in React. While I can successfully add new items, the removal process is not working as expected. The current remove function removes all elements, but I only wan ...

What steps can I take to troubleshoot the "Element type is invalid" error in my React application?

I am currently restructuring my initial code for better organization. Click here to view the code on CodeSandbox. However, I'm facing issues with integrating child components into my code. For example, in this instance, I showcase how I import a chi ...

What is the process for importing a JavaScript file into a Vue component?

Having trouble importing JSON results into a Vue component? The results are as follows: [{"id":"d023c5e3-ca3c-4d97-933a-1112a8516eee", "score":9001, "updated":"2018-12-07T13:48:33.6366278", "player":Johanna, "category":Funny}, {"id":"398b65fb-e741-4801-b ...

Tips for accessing files following the transmission of a post request within the req.body

Encountering a problem where image uploads to an s3 bucket are not successful. The error message received is: API resolved without sending a response for /api/upload/uploadPhoto, this may result in stalled requests. The front end includes an input that ca ...

exchanging a library for a different one

I'm faced with a relatively simple task here, but as I am just beginning to delve into object-oriented programming, it is proving to be quite perplexing for me. Currently, I am using the lon_lat_to_cartesian function from the following source: functi ...

Generate an array of objects by combining three separate arrays of objects

There are 3 private methods in my Angular component that return arrays of objects. I want to combine these arrays into one array containing all the objects, as they all have the same class. Here is the object structure: export class TimelineItemDto { ...

Begin anew with Flip.js

Currently, I am incorporating the jquery flip plugin from nnattawat.github.io/flip to establish a card flipping mechanism on my website. I have successfully implemented the method outlined in the documentation to unregister the flip event from the elemen ...

What is the best method for including parameters in OBJECT_URL when sharing a post on Facebook?

Regarding this line: FB.api('/me/namespace:read' + '?article=http://www.xxxxxxxxxxxxxx/tm/redir.php&access_token=','post', Whenever I attempt: I encounter errors. How can I successfully pass parameters in the OBJECT_UR ...

Switch up the sequence of selected/appended SVGs in D3

In this dot matrix visual example, different colored circles represent funding percentages from three countries: USA, Canada, and Mexico. The gray circles indicate the remaining funding to be raised. The code snippet showcases how the circles are mapped ba ...

Baffled by the data visualization produced by Google Chart using information from

Perhaps I'm being a bit ambitious, but I managed to create a basic Chart using GoogleCharts. The problem is that I have to input the values manually, but I want to retrieve them from the Database. I know JSON can accomplish this, but I've spent f ...