Max Nelson Max Nelson - 27 days ago 6
Javascript Question

How can I get an array element out of an array in the value of a form element?

I have an html form element with its value set as an array. I want to get one of these values out of the array via jQuery. How is this done? Here is my code. Maybe it can speak for itself if my explanation wasn't clear. Thank you!

var lat = 0;
var long = 0;

//gets the latitude and longitude when a user clicks on any place on the map

map.on('click', function(e) {
lat = e.latlng.lat;
long = e.latlng.lng;

//store the lat and long in an array

var latlong = [lat, long];

//here I am setting the value of my an element in my form as the array of lat and long

document.getElement(".<?= $this->getName() ?>").set("value", latlong);
var getLatlong = jQuery(".<?= $this->getName() ?>").val();
console.log("retrieved: " + getLatlong);

//it saves and retrieves properly.

//THE PROBLEM IS HERE
//THE PROBLEM IS HERE
var lat = $(".<?= $this->getName() ?>").val()[0];
var long = $(".<?= $this->getName() ?>").val()[1];
//THE PROBLEM IS HERE
//THE PROBLEM IS HERE


});


This all runs fine but I do not get the reuslt I want. If i try using any of the lines of code below

//THE PROBLEM IS HERE
var lat = $(".<?= $this->getName() ?>").val()[0]; //returns 9
var long = $(".<?= $this->getName() ?>").val()[1]; //returns 4
var long = $(".<?= $this->getName() ?>").val()[3]; //returns 2
var long = $(".<?= $this->getName() ?>").val()[4]; //returns 3
//THE PROBLEM IS HERE


to get either the latitude or the longitude "ie: 94.2323, 12.9932"

The index [0] returns 9,
the index [1] returns 4,
the index [3] returns 2


as if the 94.2323 is the array instead of the lat and long as the array. I want [0] to return 94.2323, and [1] to return 12.9932.

I tried explaining this and formatting this question the best I could. Thank you.

Answer

You can use JSON.stringify() to convert Array to JSON format

document.getElement(".<?= $this->getName() ?>")
.set("value", JSON.stringify(latlong));

JSON.parse() to convert JSON formatted String to Array

var getLatlong = JSON.parse(jQuery(".<?= $this->getName() ?>").val());
console.log(getLatlong[0], getLatlong[1]); // do stuff
Comments