bf16
bf16

Reputation: 37

javascript get id value into variable

I have used an api to get some information about someone who visits my page. The data is returned into a JSON format and I have used the .html function to set the content into some IDs like this:

$.getJSON("http://ip-api.com/json/?callback=?", function (data) {
    $("#lat").html(data.lat);
    $("#lon").html(data.lon);
});

Using:

<p id="lat"></p> 
<p id="lon"></p>

in my html body, I can see that the data has been set and is printed in my browser.

My question is how can I retrieve the data that is printed from the IDs into another, separate variable to continue to use/pass of to other functions ? I have tried using different functions like getElementById() etc. but none have worked.

Upvotes: 0

Views: 2393

Answers (1)

xyhhx
xyhhx

Reputation: 6664

You can use $(element).html() to get contents of an element.

For example:

var someHtml = "<p>Hello world!</p>";

$(someElement).html(someHtml); 
// This will set the html to be "<p>Hello world!</p>"

alert( $(someElement).html() );
// This will return "<p>Hello world!</p>" in the alert box!

To directly answer your question:

var coords = {
    // lat coord
    'lat' : $("#lat").html(),

    // long coord
    'lon' :$("#lon").html()
};

You can then reference them with coords.lat and coords.lon

That being said!

There's really no reason to set the coords variable based on the HTML elements' values. Even if you have to display them, you'd be better off saving the variable directly from the API response to shave off some milliseconds.

So you might do this:

var coords = {};
$.getJSON("http://ip-api.com/json/?callback=?", function (data) {
    $("#lat").html(data.lat);
    $("#lon").html(data.lon);
    coords = { 'lat' : data.lat, 'lon' : data.lon };
});

Edit:

As per your pastebin example - your error is coming from two places:

1. You are trying to affect the #map div before it is rendered

Firstly, move all your scripts to be below your HTML, so you will have <div id="map"></div> right next to <table id="GeoResults"></table>

Lines 22-27 become:

<table id="GeoResults"></table>

<p id="lat"></p>
<p id="lon"></p>

<div id="map"></div>

2. You are references latitude before it is set.

On lines 61 and 62 you try console.log() and document.write() to see the variable latitude. It is not defined until immediately after:

        console.log(latitude);
        document.write(latitude);

        var coords = {
            // lat coord
            'lat' : $("#lat").html(),

            // long coord
            'lon' :$("#lon").html()
        };

So that obviously won't work - just move those lines until after you define latitude and you're golden.

Try out the updated HTML

Upvotes: 3

Related Questions