textarea中的文本不应出现在禁用的输入文本元素中

时间:2017-02-20 03:29:50

标签: javascript html

当我在textarea中输入文本时,即使它被禁用,它也会被复制到输入文本元素中。我希望文本只出现在未禁用的输入文本元素中。

http://codepen.io/vincent119/pen/rjgxqm

提供完整代码

HTML:

<textarea id="batch_full" oninput="text_to_table()" onkeypress="enterpressalert(event, this)" placeholder="Batch input here" wrap="off"></textarea><br>

<table id="results_table" oninput="table_to_text()">
  <tr>
    <th>Type</th>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
    <th>Column 4</th>
  </tr>
  <tr>
    <td><select id="Signer_Type" name="Signer_Type" onchange="Select_Signer_type()">
        <option value="Business">
          Business
        </option>
        <option selected value="Consumer">
          Consumer
        </option>
      </select></td>
    <td><input id="c1" maxlength="5" type="text"></td>
    <td><input id="c2" maxlength="5" type="text"></td>
    <td><input id="c3" maxlength="5" type="text"></td>
    <td><input id="c4" maxlength="5" type="text"></td>
  </tr>
</table>

JavaScript:

    function table_to_text() {
      var j;
      var z = document.getElementById("batch_full").innerHTML;
      var k = document.getElementsByTagName("td").length;
      z = '';
      var article1 = new Array();
      for (j = 1; j <= k; j++) {
        article1[j] = document.getElementById("c" + j).value;
        z = z + article1[j];
      }
      document.getElementById("batch_full").value = z;
    }

    function text_to_table() {
      var batch_text = document.getElementById("batch_full").value;
      var length_covered = 0;
      var n = document.getElementsByTagName("td").length;
      var article = new Array();
      var temp;
      var length;

      var numberOfLineBreaks = (batch_text.match(/\n/g) || []).length;
      for (var i = 1; i <= n; i++) {
        article[i] = document.getElementById("c" + i);
        length = article[i].getAttribute('maxlength');
        temp = batch_text.substr(length_covered, length);
        article[i].value = temp;
        length_covered = Number(length_covered) + Number(length);
      }
    }

    function Select_Signer_type() {
      var option = document.getElementById("Signer_Type");
      if (option.value == "Business") {
        document.getElementById('c1').disabled = true;
        document.getElementById('c2').disabled = true;
        document.getElementById('c3').disabled = false;
        document.getElementById('c4').disabled = false;
      } else {
        document.getElementById('c3').disabled = true;
        document.getElementById('c4').disabled = true;
        document.getElementById('c1').disabled = false;
        document.getElementById('c2').disabled = false;
      }
    }

1 个答案:

答案 0 :(得分:0)

正如您所注意到的,禁用的输入字段仍然可以有值,并且仍然可以通过Javascript分配。您需要做的是修改text_to_table功能,以考虑下拉列表中选定的值是Business还是Consumer

var option = document.getElementById("Signer_Type");
var startIndex = (option.value == "Businesss") ? 3 : 1;

for (var i = startIndex; i <= n; i++) {
  ...
}