开发者

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 c开发者_开发技巧alled 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


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜