首页 > 解决方案 > 复选框文本到文本区域

问题描述

我需要有很多可以通过复选框选择的句子,它们会立即出现在它们下方的文本区域中。在 textarea 上可以更改句子,然后将 textarea 导出为 docx 和 pdf。我从用户dinheiro的 Sitepoint.com 论坛中找到了 2007 年的这个不错的脚本。

每个句子都应该在自己的行和句子之间换行。添加句子时一切顺利,但删除句子时,句子之间会丢失换行符。我已经在线对原始脚本进行了一些更改

df[1][0].value+=this.name+'\n\n ';

原来是 df[1][0].value+=this.name+' ';

并添加了一行df[1][0].value=df[1][0].value.replace(/\n/g, '');

任何人都可以帮助解决这个问题,或者有没有人有更好的解决方案来做到这一点?谢谢!

window.onload = function() {
  df = document.forms;
  inp = df[0].getElementsByTagName('input');
  for (c = 0; c < inp.length; c++) {
    if (inp[c].type == 'checkbox') {
      inp[c].onclick = function() {
        if (this.checked == true) {
          df[1][0].value += this.name + '\n\n ';
        } else {
          df[1][0].value = df[1][0].value.replace(/\n/g, '');
          df[1][0].value = df[1][0].value.replace(this.name + ' ', '');
        }
      }
    }
  }
}
<form action="#">
  <div>
    <input type="checkbox" name="- foo" />foo<br>
    <input type="checkbox" name="- blah" />blah<br>
    <input type="checkbox" name="- dodah" />dodah<br>
  </div>
</form>

<form action="#">
  <div>
    <textarea cols="20" rows="10"></textarea>
  </div>
</form>

将复选框文本添加到 textarea、编辑 textarea 上的文本、添加一些额外文本并将其与其他字段一起发送到处理程序怎么样?

标签: javascripthtml

解决方案


问题是这一行正在删除使文本出现在同一行中的换行符

df[1][0].value=df[1][0].value.replace(/\n/g, '');

因此,我只提供与要删除的特定单词相关的换行符:

df[1][0].value=df[1][0].value.replace(this.name+'\n\n','');

这是工作代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    
    <script type="text/javascript">
    
    window.onload=function() {
        
        df=document.forms;
        inp=df[0].getElementsByTagName('input');
    for(c=0;c<inp.length;c++) {
    if(inp[c].type=='checkbox') {
        inp[c].onclick=function() {
        debugger;
    if(this.checked==true){
        df[1][0].value+=this.name+'\n\n';
    }
    else {
        df[1][0].value=df[1][0].value.replace(this.name+'\n\n','');
          }
         }
        }
       }
      }
    </script>
    
    </head>
    <body>
    
    <form action="#">
        <div>
            <input type="checkbox" name="- foo"/>foo<br>
            <input type="checkbox" name="- blah"/>blah<br>
            <input type="checkbox" name="- dodah"/>dodah<br>
        </div>
    </form>
    
    <form action="#">
        <div>
            <textarea cols="20" rows="10"></textarea>
        </div>
    </form>
    
    </body>
    </html>


推荐阅读