2

I'm currently trying to populate some location data for google maps initialization, So to an HTML input field I assign it with an JavaScript array format so that I use it for google maps but all in vein. . . . Here is my Code

      <input id="a" name="a" value='["WAPDA Town, Lahore, Pakistan","31.4311985","74.26435820000006","1"],["Johar Town, Lahore, Pakistan","31.469693","74.27284610000004","2"],'>

then I further Call it in my script to initialize it for locations.

 var location = '[' + document.getElementById('a').value + ']';

but it is not giving my desire result as I know I'm doing wrong. but what is the proper way of initalizing it? Any Suggestion

6
  • 2
    use JSON.parse. var location = JSON.parse('[' + document.getElementById('a').value + ']'); (but you need to get rid of the trailing ',' at the end). document.getElementById('a').value.slice(0, -1) will remove the trailing ',' Commented Aug 22, 2019 at 20:12
  • 1
    Why are you putting that array in an <input> element in the first place? Commented Aug 22, 2019 at 20:14
  • 1
    @Pointy the input value doesn't have a '[ ]' Commented Aug 22, 2019 at 20:15
  • @Pointy input value has multiple array seperated by ','. so we need to wrap the value with '[]' Commented Aug 22, 2019 at 20:18
  • @ajaiJothi Answer Worked for me I'm keep searching for this for last two hours save my day :D Commented Aug 22, 2019 at 20:23

1 Answer 1

1

Try (I remove last comma from your input)

var loc = JSON.parse(`[${a.value}]`);

console.log(loc);
 <input id="a" name="a" value='["WAPDA Town, Lahore, Pakistan","31.4311985","74.26435820000006","1"],["Johar Town, Lahore, Pakistan","31.469693","74.27284610000004","2"]'>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks This is also a right answer thanks, But why we use JSON.parse while getting array from HTML input field
@NaveedCheema because the value of an input is always a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.