views:

40

answers:

3

Hi I'm trying to implement a solution that was posed on this question: http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery

But coming unstuck.

This flat function works fine when adding some dummy text into a textarea element:

function add_to() {
        $('#ad_textarea').val($('#ad_textarea').val()+'test');
}

However, when I try to wire up this function to a variable, it breaks:

function add_to(word) {
            $('#ad_textarea').val($('#ad_textarea').val()+word);
    }

when being called from this line of code:

<?php foreach ($words as $word) {
    echo    "<li class='$word[0]'><a href='#' onclick='add_to('$word');'>$word</a></li>";
    } 
    ?>

I have looked at the outputted code, and it looks clean:

<li class='a'><a href='#' onclick='add_to('aardvark');'>aardvark</a></li>

I'm ultimately trying to get aardvark to print out in the textarea. Can anyone spot my slip up?

TIA

+5  A: 

You need to escape the value, or change quotes if you're sure it won't have any in the string itself, like this:

 onclick='add_to("$word");'

However, it'd be better to use unobtrusive script and eliminate this problem at the same time, like this:

<li class='a'><a href='#' class='word'>aardvark</a></li>

Then use script like this:

$(function() {
  $("a.word").click(function() {
    $('#ad_textarea').val($('#ad_textarea').val()+$(this).text());
  });
});

Or use .val() with a function:

$(function() {
  $("a.word").click(function() {
    var t = $(this).text();
    $('#ad_textarea').val(function(i, v) { return v + t; });
  });
});
Nick Craver
+2  A: 

You have unescaped single quotes in your "onclick". Either use double quotes or escape them. Or you can even use double quotes outside, single quotes inside.

Greg
doh! schoolboy. cheers
The Pied Pipes
A: 

Change

"<li class='$word[0]'><a href='#' onclick='add_to('$word');'>$word</a></li>";

to

"<li class='$word[0]'><a href='#' onclick=\"add_to('$word');\">$word</a></li>";

and check may be it works

Actually

onclick='add_to('aardvark');'

should be

onclick="add_to('aardvark');"
Salil