The Pied Pipes
The Pied Pipes

Reputation: 1435

JS: adding text to text area issue

Hi I'm trying to implement a solution that was posed on this question: 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

Upvotes: 0

Views: 107

Answers (3)

Salil
Salil

Reputation: 47472

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');"

Upvotes: 0

Greg
Greg

Reputation: 7922

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.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630349

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; });
  });
});

Upvotes: 5

Related Questions