0

There are times tha i feel so frustrated when trying to do simple things with Jquery. I have a textarea where user can write own things but can also chose from some predefined phrases and add them too

so html looks like

<textarea id="id_text"></textarea>
<div id="predef-phrases>
    <input type="checkbox"><label>checkbox1</label> 
    <input type="checkbox"><label>checkbox2</label>
    <input type="checkbox"><label>checkbox3</label>
    <input type="checkbox"><label>checkbox4</label>     
</div>
<input type="button" id="add" name="add" value="Add phrases" />

and the jquery is like this:

$(document).read(function(){
      $("#add").click(function(){
        $("#predef-phrases input[type=checkbox").each(function(i, checkbox){
            if($(checkbox).is(":checked")){
                text_value = $("#id_text").val();
                checkbox_text = $(checkbox).next('label').text();
                $("#id_text").append(checkbox_text+'\n');

            }
        });
    });
});

Everything works fine up until the user types some text. Then the predefined phrases are not appended in textarea when user presses the add button. Am i missing something?

4

2 回答 2

1

不要使用append,这只会更改“初始”值,而是直接更改值:

$("#id_text")[0].value += checkbox_text+'\n';

如果您愿意,也可以使用以下val功能:

$("#id_text").val(function(_,text){ return text+checkbox_text+'\n'});

但是您的 HTML(缺少右引号)和选择器(缺少右大括号)中也有错误。这是一个固定的代码

于 2013-11-05T10:33:57.077 回答
0

您不应该将 append() 用于 textarea。相反,您可以尝试以下方法:

$("#id_text").val($("#id_text").val() + '\n' + checkbox_text);
于 2013-11-05T10:50:36.893 回答