如何将一个文本区域分成两个textareas?

时间:2017-04-27 08:16:30

标签: javascript html split

我将两个文本区域值连接成一个文本区域值。现在,当我点击恢复按钮时,我想将文本区域拆分为旧的两个文本区域。 Html视图图像和代码如下: HTML View

HTML:

<div class="container">
  <h3 class="text-center text-primary">TextArea Concatenate and Revert</h3>
  <div class="row">
    <div class="col-md-5">
      <div class="row">
        <div class="col-md-12">
          <textarea rows="4" cols="50" id="text_area_1"></textarea>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12">
          <textarea rows="4" cols="50" id="text_area_2"></textarea>
        </div>
      </div>
        <button type="button" class="btn btn-success" onclick="concatenate()">Concatenate</button>
    </div>
    <div class="col-md-5">
      <textarea rows="8" cols="100" id="text_area_3"></textarea>
      <input type="submit" class="btn btn-warning" value="Revert">
    </div>
  </div>
</div>

使用Javascript:

<script>
  function concatenate(){
    document.getElementById("text_area_3").value =
    document.getElementById("text_area_1").value + " " +
    document.getElementById("text_area_2").value;
    }
</script>

2 个答案:

答案 0 :(得分:2)

您应该使用分隔符,以便可以将值拆分回textareas。

<script>
var one = document.getElementById("text_area_1");
var two = document.getElementById("text_area_2");
var three = document.getElementById("text_area_3");

function concatenate(){
  three.value = one.value + ":" + two.value;
  one.value = "";
  two.value = "";
  }

function revert(){
    var val = three.value.split(":");
    one.value = val[0];
    two.value = val[1];
    three.value = "";
    }
</script>

请参阅我创建的示例:https://jsfiddle.net/ft05wyxt/

答案 1 :(得分:1)

使用长度可以执行以下操作

var textbox1="testt ttets tetstend__";
var textbox2="my second textbox2";

//added a space between;
var mergedTextbox=textbox1+' '+textbox2;

console.log(textbox1.length,textbox2.length,mergedTextbox.length);

var splited1=mergedTextbox.substr(0,textbox1.length);
var splited2=mergedTextbox.substr((textbox1.length+1),textbox2.length);

console.log(splited1,splited2)