我正在尝试使用jscript从另一个textarea复制数据后清除textarea但无法清除第二个textarea

时间:2017-12-04 20:50:09

标签: javascript jquery html

<!DOCTYPE html>
<html>
<body>

<b>Q1.</b> 
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

<p>If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer</p>

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText()" value="New Answer">

<p><textarea readonly rows="4" columns="200" id="A1"></textarea>

<script>
function clearText() {
    document.getElementById("A1").reset();
}

function SameAnswer() {
   var x = document.getElementById("Q1_Old").value;
   document.getElementById("A1").innerHTML = x;
}
</script>

</body>
</html>

在上面的代码中,SameAnswer()函数正常工作但ClearText()函数不正常。需要帮助解决此问题

2 个答案:

答案 0 :(得分:0)

重置是针对整个表单。所以你有两个选择。

1)将值设置为空字符串

document.getElementById("A1").value = "";

2)将值设置为等于默认值

var ta = document.getElementById("A1");
ta.value = ta.defaultValue;

当你设置值时,你需要使用值,而不是innerHTML。

&#13;
&#13;
function clearText1() {
  var ta = document.getElementById("A1");
  ta.value = "";
  ta.removeAttribute("readOnly")    
}

function clearText2() {
  var ta = document.getElementById("A1")
  ta.value = ta.defaultValue;
  ta.removeAttribute("readOnly")    
}


function SameAnswer() {
   var x = document.getElementById("Q1_Old").value;
   var ta = document.getElementById("A1");
   ta.value = x;
   ta.setAttribute("readOnly", true)
}
&#13;
<b>Q1.</b> 
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

<p>If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer</p>

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText1()" value="New Answer 1">
<input type="button" onclick="clearText2()" value="New Answer 2">

<p><textarea readonly rows="4" columns="200" id="A1"></textarea>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

更改.document.getElementById(“A1”)。reset(); to document.getElementById(“A1”)。value =“”;

function clearText() {
    document.getElementById("A1").value = "";
}

function SameAnswer() {
   var x = document.getElementById("Q1_Old").value;
   document.getElementById("A1").innerHTML = x;
}
<b>Q1.</b> 
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

<p>If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer</p>

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText()" value="New Answer">

<p><textarea readonly rows="4" columns="200" id="A1"></textarea>