如何从表单元素的值中获取数组中的数组元素?

时间:2016-11-06 00:19:16

标签: javascript php jquery forms

我有一个html表单元素,其值设置为数组。我想通过jQuery从数组中获取其中一个值。这是怎么做到的?这是我的代码。如果我的解释不清楚,也许它可以说明问题。谢谢!

    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


    });

这一切都运行良好,但我没有得到我想要的重新开始。如果我尝试使用下面的任何代码行

    //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

获得纬度或经度“ie:94.2323,12.9932”

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

好像94.2323是数组而不是lat而长数组。我希望[0]返回94.2323,[1]返回12.9932。

我尝试解释这个并尽可能地格式化这个问题。谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用JSON.stringify()Array转换为JSON格式

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

JSON.parse()JSON格式String转换为Array

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