3

I want print the dict a in alert , (it is possible?) or print in the third's textarea (three) with id=p. I read on this question and I used

document.getElementById("p").value=JSON.stringify(a);;
    alert("myObject is " + a.toSource());
    console.log(a);

These not function. The example is :

<!DOCTYPE HTML>
<html>
<head>
<title>Example - print the dict</title>
</head>
<body>

<input id = 'button1' type = 'button' value = 'print the dict' onclick="updateHistory()"/>

<script type = 'text/javascript'>

var count ="?foo=1&oo=298529982";

function updateHistory()
{

 var a = new Array();

for (var i = 0; i < document.formparam.elements.length; i++)
{

    var field = document.formparam.elements[i];
    a[field.name] = field.value;
}

document.getElementById("p").value=JSON.stringify(a);;
alert("myObject is " + a.toSource());
console.log(a);
}


</script>
<form method="GET" name="formparam" id="formparam" ><table><tr><td><textarea name="name" >john</textarea></td><td><textarea name="surname">jackold</textarea></td></tr></table></form>
<textarea id="p"></textarea>
</body>
</html>
Community
  • 1
  • 1
Mirko Cianfarani
  • 2,023
  • 1
  • 23
  • 39

2 Answers2

3

Using JSON.stringify() on an array will iterate over the array like so:

for (var i = 0; i < a.length; ++i) {
    // process value of a[i]
}

But because you're adding properties to the object using a[field.name], those are not added to the list of array items, unlike a.push(value). As such, JSON.stringify() will print [].

You should either:

  1. Define a as an object, i.e. var a = {};

  2. Iterate over the keys yourself:

    for (var k in a) {
        if (a.hasOwnProperty(k)) {
            // process value of a[k]
        }
    }
    
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

var a = new Array();

should be

var a = {}; or var a = new Object();

There are no dictonnaries in JavaScript, however, you can use an object as a key/value store. To alert the object as JSON, you can just do alert(JSON.stringify(a));.

plalx
  • 42,889
  • 6
  • 74
  • 90