【发布时间】:2014-09-25 20:55:54
【问题描述】:
我有一些复选框可以在文本区域中生成文本。我希望用户能够在区域内添加或编辑生成的文本,然后继续添加更多自动生成的文本。
我无法“保存”所做的任何编辑。 It seems that I can listen for changes in the textarea via the $('textarea').change(function(){ set text variable to textarea value. construct, but I keep returning the original values when additional checkboxes are selected.
我的 HTML:
<input type='checkbox' id='line1'>Some text
<br>
<input type='checkbox' id='line2'>more text
<br>
<input type='checkbox' id='line3'>even more text
<br>
<textarea id='output' placeholder='1st textarea' rows=10 cols=20></textarea>
<br>
我的文本生成代码的相关位:
var texts = {
line1: 'some text',
line2: 'more text',
line3: 'even more text'
};
// temporary holder for checkbox id
var part_choice = null;
// new textarea variables
var first_text = $('#output').val();
// old text variable
var text_old = '';
// fill texts in the textbox
function print_text() {
if (part_choice !== null) {
first_text += texts[part_choice] + '\n';
part_choice = null;
$('#output').val(first_text);
}
}
// Retain any manual edits within textarea
$('#output').change(function () {
first_text = $('#output').val();
});
$('input:checkbox').change(function () {
if ($(this).is(':checked')) {
part_choice = $(this).attr('id');
text_old = first_text;
print_text();
} else {
var del = $(this).attr('id');
text_old = first_text.replace(texts[del] + '\n', '');
first_text = text_old;
$('#output').val(text_old); // undo function, textarea = prior text
}
});
现在错误代码已修复 - 后续问题:我想使用 jquery 和按键触发事件来模拟手动编辑。我能够执行在文本区域中按下“空格键”的模拟。这应该在选择下一个项目之前保存 textarea 内容,但事实并非如此。只有物理按键似乎有效?什么给了?
【问题讨论】: