I have a jquery variable like this :
var d1 = [{text:'t1',value:'1'},{text:'t2',value:'2'},{text:'t3',value:'3'},{text:'t4',value:'4'}];
console.log(d1);
When i display it in console.log, i have something similar to the image below
Now if i had an input in html like this :
<input id="txtstr" name="txtstr" value="[{text:'t1',value:'1'},{text:'t2',value:'2'}, {text:'t3',value:'3'},{text:'t4',value:'4'}]" type="text" />
in console.log i have :
console.log($("#txtstr").val());
I want to have json array in console.log when i use input (Like the first picture). I have also used json.parse but it didn’t work.
>Solution :
It is because the attribute value isn’t having a value quoted, you don’t put text and value in quotes. to fix this do the following
<input id="txtstr" name="txtstr" value='[{"text":"t1","value":"1"},{"text":"t2","value":"2"},{"text":"t3","value":"3"},{"text":"t4","value":"4"}]' type="text" />
<script>
var inputString = $("#txtstr").val();
var jsonArray = JSON.parse(inputString);
console.log(jsonArray);
</script>
So in pure JavaScript
<input id="txtstr" name="txtstr" value='[{"text":"t1","value":"1"},{"text":"t2","value":"2"},{"text":"t3","value":"3"},{"text":"t4","value":"4"}]' type="text" />
<script>
var inputString = document.getElementById("txtstr").value;
var jsonArray = JSON.parse(inputString);
console.log(jsonArray);
</script>

