tags:

views:

3519

answers:

2

My form in the html DOM is a checkbox to click (there can be more than one). The problem occurs in the description string when ever I use an apostrophe, since my list object is single-quote deliniated. This is one of the checkboxes in the form:

<input type="checkbox" id="cbx" name="cbx" value="{'getPic': 'url', 'picsrc': 'http://lh3.ggpht.com/_ZB3cttqooN0/SVmJPfusGWI/AAAAAAAADvA/GuIRgh6eMOI/Grand%20Canyon%201213_121508214.JPG', 'pos': None, 'description': 'Here's what it REALLY looks like at 5:30am!  Bring your headlight!'}">

The javascript that reads the values of the checked checkboxes and pushes them into an array (list):

var pylist = [];
    for (i=0; i<document.picList.cbx.length; i++) {

           if (document.picList.cbx[i].checked) {
              pylist.push( document.picList.cbx[i].value );
           }
    }

var getstr = JSON.stringify(pylist);

The problem is always that getstr at this point has chopped off everthing after the single quote in the description property. I've tried different ways of escaping it to little avail.

A: 

The problem is that the value of the checkbox already is a JSON string. One solution would be to call JSON.parse() on the value:

var pylist = [];
    for (i=0; i<document.picList.cbx.length; i++) {

           if (document.picList.cbx[i].checked) {
              pylist.push( JSON.parse( document.picList.cbx[i].value) );
           }
    }

var getstr = JSON.stringify(pylist);
Philippe Leybaert
A: 

I've run into the same issue - we stick json in a hidden field so we don't have to query the server on every page. We replace apostrophes with a "code" before putting into the html - we added a javascript function that replaces the code with an apostrophe.

Really hacky, but it works really well. Of course, we have one place in the code that gets json from the server and one place where javascript needs to parse it - if you find you're repeating the methods throughout your code, your mileage will vary.

Todd R