April 9, 2012

Why is my jQuery code not able to read an apostrophe?

Question by the_boy_za

I have a web form that automatically checks the checkboxes when the page loads based on the data stored in the MYSQL database. Everything works just fine with the exception of data that contains an apostrophe. Here’s my code:

JSON:

 [{"pkFavorietemerken":"1","merken":"Adidas"},{"pkFavorietemerken":"2","merken":"Boss"},{"pkFavorietemerken":"3","merken":"Burberry"},{"pkFavorietemerken":"4","merken":"Christian Dior"},{"pkFavorietemerken":"5","merken":"D&G"},{"pkFavorietemerken":"6","merken":"Diesel"},{"pkFavorietemerken":"7","merken":"Dolce & Gabanna"},{"pkFavorietemerken":"8","merken":"Emporio Armani"}]

JQUERY:

   $.getJSON("jason.php", function(data) {

      $.each(data, function(){


     $("[value='" + this.merken + "']").attr("checked","checked");


       });

   });

HTML:

    <form name="form1" method="post" action="something.php">                        
    <ul>
        <li><input type="checkbox" name="merk[]" value="Adidas"/>Adidas</li>
        <li><input type="checkbox" name="merk[]" value="Airforce"/>Airforce</li>
        <li><input type="checkbox" name="merk[]" value="Armani"/>Armani</li>
        <li><input type="checkbox" name="merk[]" value="Asics"/>Asics</li>
        <li><input type="checkbox" name="merk[]" value="Bikkemberg"/>Bikkemberg</li>
        <li><input type="checkbox" name="merk[]" value="Bjorn Borg"/>Bjorn Borg</li>
        <li><input type="checkbox" name="merk[]" value="BlueBlood"/>BlueBlood</li>
        <li><input type="checkbox" name="merk[]" value="Boss"/>Boss</li>
        <li><input type="checkbox" name="merk[]" value="Brunotti"/>Brunotti</li>
        <li><input type="checkbox" name="merk[]" value="Burberry"/>Burberry</li>
    </ul>

THIS DOESN’T WORK:

    <li><input type="checkbox" name="merk[]" value="Levi's"/>Levi's</li>

Answer by AKX

For Levi's, the resulting selector ends up being "[value='Levi's']". I guess the selector engine chokes on it. I’m not sure if it supports escaping (Levi's) — if it doesn’t, you can do something like

var merken = this.merken;
$("input:checkbox").each(function(){
    if(this.value == merken) this.checked = true;
});

instead.

Answer by Starx

The problem is of the apostrophe, you have to escape it.

Here is a simply way to do so

function addslashes( str ) {
    return (str+'').replace(/([\"'])/g, "\$1").replace(//g, "\0");
}
$("[value='" + addslashes(this.merken) + "']").attr("checked","checked");
...

Please fill the form - I will response as fast as I can!