user974896
user974896

Reputation: 1813

Double quotes breaking jQuery (Very simple)

    <?

    //SQL SELECT HERE

    $result = mysql_query($sql);

    $options = '';
    while ($row = mysql_fetch_array($result)) {
        $options .= '<option>Data: ' . $row['data'] .'</option>';
    }
    ?>
    $("#multiSelect").html("<?=$options?>");

The above is a PHP query inlined in a javascript function. It's goal is to populate a multiselect. The issue is that when $row['data'] contains something with double quotes jQuery doesn't like it and complains. When I remove the row containing double quotes it works fine.

How can I get around this? Is this normal behavior of jQuery.

Upvotes: 0

Views: 1090

Answers (3)

andrewsi
andrewsi

Reputation: 10732

It's because your call is being coming out as something like:

$("#multiSelect").html(""Hello"");

Most programming languages will have problems with that - they assume that the first quote you're adding ends the string you're passing in, and that the next text should be a valid piece of code.

You can get around it by escaping the quotes, removing them, or substituting them to something else:

$("#multiSelect").html("<?=addslashes($options)?>");    
$("#multiSelect").html("<?=str_replace('"', '', $options)?>");    
$("#multiSelect").html("<?=str_replace('"', '\'', $options)?>");    

Depending on what the input text is likely to be.

Upvotes: 1

epascarello
epascarello

Reputation: 207511

WHY WHY WHY would you build the options with the code behind and than set it with jQuery? Why can't PHP just set it itself?

You need to escape the quotes with a \

"Man it is \"hot\" in here"

Upvotes: 0

Mantas Vaitkūnas
Mantas Vaitkūnas

Reputation: 744

Try to addslashes: http://php.net/manual/en/function.addslashes.php

Upvotes: 2

Related Questions