views:

55

answers:

2

Hi there, trying to learn json due to work req...i am trying to add and delete records to json object dynamically...can some one tell me why i keep getting UNDEFINED message....here is the code..thanks for the help!!

<html>
<head>
<title>TEST</title>
<script language="Javascript" type="text/javascript">
 function addC(){


  var index = document.getElementById('type').selectedIndex;
  var type = document.getElementById('type').options[index].value;
  var name = document.getElementById('inpName').value;
  var date = document.getElementById('inpDate').value;

  processJson(type,name,date);

  return false;
 }

 function processJson(type,name,date){

  var count = document.getElementById('counter').value*1;
  var currentRecords = document.getElementById('holder').value;
  var newRecordType = "{\"name\":\""+type+"\",";
  var newRecordName = "\"type\":\""+name+"\",";
  var newRecordDate = "\"date\":\""+date+"\"}";
  var newRecord = newRecordType + newRecordName + newRecordDate;

  if(count > 0){
   newRecord = "," + newRecord;
  }
  var updatedRecord = currentRecords + newRecord;


  var jsonObj = {"allrows" : "["+updatedRecord+"]"};
  document.getElementById('counter').value=(document.getElementById('counter').value *1)+ 1;
  document.getElementById('holder').value=updatedRecord;  
 }

 function deleteRow(){
  var toDel = document.getElementById('inpDel').value;
  alert(toDel);
  var current = "[" + document.getElementById('holder').value + "]";
  alert(current);
  var jsonO = {"allRows" : current};
  alert(jsonO);
  var t = jsonO.allRows[toDel].type;
  alert("Deleting - " + t);
  return false;  
 }

</script>




</head>

<body>
<form name="frm" action="">
<table>
 <tr>
  <td>
   <select name="type" id="type">
    <option value="creator">Creator</option>
    <option value="editor">Editor</option>
    <option value="publisher">Publisher</option>
   </select>
  </td>
  <td>
   <input type="text" name="inpName" id="inpName" value="">
  </td>
  <td>
   <input type="text" name="inpDate" id="inpDate" value="">
  </td>
  <td>
   <input type="text" name="inpDel" id="inpDel" value="">
  </td>
  <td>
   <input type="button" name="cmdAdd" value="Add" onClick="return addC();">
   <input type="button" name="cmdAdd" value="Del" onClick="return deleteRow();">
  </td>
 </tr>
 <tr>
  <td><input type="text" name="counter" id="counter" value="0">
 </tr>
 <tr>
  <td colspan="3"> 
   <textarea name="holder" id="holder" rows="20" cols="60"></textarea>

  </td>
 </tr>
</form>
</body>
</html>
A: 

That's not JSON you're playing with. That's javascript objects. Granted JSON stands for "javascript object notation" but it generally refers to serialized objects sent over the wire.

OK, so an introduction to object literals in javascript:

  1. An object has the format { key : value, key : value } where the key part does not need to be quoted if it is not a keyword.

  2. An array has the format [ value, value ].

  3. Arrays are implemented as objects.

  4. To access a value in an object, use one of the following notation:

    object.key
    object['key']
    

    note that the second notation means you can use a variable as the key.

  5. Since arrays are just objects, you access values in arrays the same way:

    array[index]
    

So, to do what I think you're trying to do I would do it like this:

First, a simple function to turn objects to a string:

// WARNING! : simple toString function. You should probably
// use a better one
function toString (obj) {
    if (!isNaN(obj))             return ''+obj;
    if (obj === true)            return 'true';
    if (obj === false)           return 'false';
    if (obj === null)            return 'null';
    if (obj === undefined)       return 'undefined';
    if (typeof obj == 'string')  return '"'+obj+'"';
    if (obj instanceof String)   return '"'+obj+'"';
    var ret="";
    if (obj instanceof Array) {
        ret += "[";
        for (var i=0;i<obj.length;i++) {
            ret += toString(obj[i]);
        }
        ret += "]";
    }
    else {
        ret += "{";
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                ret += toString(i);
                ret += ':';
                ret += toString(obj[i]);
            }
        }
        ret += "}";
    }
    return ret;
}

Now, the rest of the code:

var counter_el = document.getElementById('counter');
var count = counter_el.value*1;

// WARNING! : eval is a quick and dirty JSON deserializer
// normally should not be used but is good enough for
// this example:
eval('var currentRecords = ' + document.getElementById('holder').value);
var newRecord = {
    name : type,
    type : name,
    date : date
}

if(count > 0){
    currentRecords.allrows.push(newRecord);
}
else{
    currentRecords = { allrows : [ newRecord ] };
}

counter_el.value=(counter_el.value*1)+ 1;
document.getElementById('holder').value=toString(currentRecords);
slebetman
A: 

There's a widely used script for use with json: http://www.json.org/js.html

jerone