Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

use javascript variable in html script

I have an AJAX function in my JavaScript like so

function getWeather(countryName) {
    const monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
    ];

    let dateObj = new Date();
    let month = monthNames[dateObj.getUTCMonth()];
    let day = dateObj.getUTCDate() - 1;
    let year = dateObj.getUTCFullYear();

    let newDate = `${month} ${day}, ${year}`;
    
    $.ajax({
        url: "assets/geojson/countryBorders.geo.json",
        type: "GET",
        dataType: "json",
        data: {
            
        },
        success: function(result) {
.... etc

Within my HTML modal for displaying the weather per country, I would like to include things such as the date.

Is there any way to use the Javascript variable newDate in the HTML script?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

something like ….?

 <div class="modal-body">
          <h6 id="capitalCity" class="modal-sub-header"></h6>
          <hr>
          <ul class="dem">
              <p class="date" id="newDate"></p>

>Solution :

Elaboration on Franco A. Torreses answer
this will be your javascript

function getWeather(countryName) {
    const monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
    ];

    let dateObj = new Date();
    let month = monthNames[dateObj.getUTCMonth()];
    let day = dateObj.getUTCDate() - 1;
    let year = dateObj.getUTCFullYear();

    let newDate = `${month} ${day}, ${year}`;
    document.getElementById('newData').textContent = newDate

And your HTML will stay the same.
document.getElementById(‘newData’) grabs the element from DOM and .textContent sets it’s text to whatever is after =. This is also superior to using .innerHTML as .innerHTML it allows for injections.

If you are after using variables in HTML, you could take a look into either frontent frameworks such as React, VueJS, Angular that allow just using {variable} or some other backend languages such as PHP.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading