【问题标题】:How can I retain edits made within the contents of a textarea?如何保留在 textarea 内容中所做的编辑?
【发布时间】: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 内容,但事实并非如此。只有物理按键似乎有效?什么给了?

【问题讨论】:

    标签: jquery textarea


    【解决方案1】:

    抱歉,刚刚在我的部分中发现了一个错字,以保留任何手动编辑。

    $('#output').change(function () {
        **frst**_text = $('#output').val();
    });
    

    显然应该读

    $('#output').change(function () {
        **first**_text = $('#output').val();
    });
    

    修复了它。

    【讨论】:

    • 我遇到的另一个问题是我是否可以使用 jquery 模拟按键(例如空格键)来触发 textarea change 事件?或者这将是一个不等同于使用键盘的静默编辑?
    【解决方案2】:

    frst_text = $('#output').val();

    应阅读:

    first_text = $('#output').val() + "\n";
    

    【讨论】:

    • 你一定在我打字的时候发现了这一点:) 这是我第一次尝试这里的答案。
    • 哈,是的,可能就是这样。既然你花时间解决了这个愚蠢的问题,我仍然会给予你信任。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多