使用val('')清除textarea

时间:2017-08-25 21:58:37

标签: javascript jquery

我使用jquery将一些默认内容放入<textarea>,但之后尝试通过重置为原始版本来实现一个按钮以清除任何新用户对<textarea>的添加内容。我尝试使用由jquery点击功能触发的.val('')来清除<textarea>,然后再次重新启动代码,但出于某种原因,我尝试重置后<textarea>仍为空白(作品第一次发现)。无法解决这个问题!

我正在努力在英语课上教授正确的逗号。在此处工作:https://codepen.io/brentsimpson/pen/EvveKw

function start() {

var text = "We need walnuts, cinnamon, sugar, and milk.";  
var newText;
var selectComma = ","; // this could be any punctuation you want
var hits = [];
var commaCheck;
var commaPlacement;
var progressBar = 0;
var offset = 0;

newText = text.replace(/,/g, '');

$("#commabox").text(newText); //writes newText to textarea
$("#commanumber").text(commanumbertext);

console.log("The sentence is " + text.length + " characters long.");

for(i = 0; i<text.length; i++){
if(text[i] === selectComma){
  commaPlace = i - offset;
  offset = offset + 1;
  hits.push(commaPlace);
    }
}

var commaNumber = hits.length;
var commanumbertext = "There should be " + commaNumber + " commas in this sentence.";
var progressBarProgress = Math.round(100 / hits.length);
$("#progressbardisplay").css('width', progressBar + "%"); // resets the progress bar

console.log("Commas were placed at these characters: " + hits);


/* code runs after keypress and checks if a comma has been placed
   at a place where one was removed */
$( "#commabox" ).keypress(function( event ) {
    commaCheck = event.which;
    console.log( commaCheck + " was pressed." );
    var caret = $("#commabox").caret();
    commaPlacement = caret["begin"]; //assigns value of begin in caret object to commaPlacement
    console.log("Comma placed at " + commaPlacement);
    checkCommaPlacement();
            });

/* this function checks if commas have been placed at the 
 right place in the string. Could probably use indexOf() here instead 
*/
function checkCommaPlacement() {
    a = hits.indexOf(commaPlacement);
    if (commaCheck === 44 && a != -1) {
        progressBar = progressBar + progressBarProgress;
    $("#progressbardisplay").css('width', progressBar + "%");
    console.log("Comma is in array at " + a);
    for (var i = a; i < commaNumber; i++){
        hits[i] += 1; // updates the array places above comma
      }} else {
    console.log("Comma incorrecly placed.") }               
   };

};

start();

$( ".btn" ).click(function() {
  $('#commabox').val('');
  start();
});

2 个答案:

答案 0 :(得分:1)

使用.val(newText)代替.text(newText)来设置textarea的文字:

$("#commabox").val(newText); //writes newText to textarea

答案 1 :(得分:0)

这应该足以满足您的目标:

$('document').ready(function() { 
  
  var $textarea = $('#textarea1');
  
  $textarea.attr('data-default-value', $textarea.val());
  
  $('#clear').click(function() {
    $textarea.val($textarea.data('default-value'));
  });
  
});
<textarea id="textarea1">Default value</textarea>

<button id="clear">Clear</button>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>