javascript - 使用 val ('' ) 清除文本区域

标签 javascript jquery

我将一些默认内容放入 <textarea>使用 jquery,然后尝试实现一个按钮来清除任何新用户对 <textarea> 添加的内容通过重置为原始。我试过使用 .val('')由 jquery 单击函数触发以清除 <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();
});

最佳答案

使用 .val(newText) 而不是 .text(newText) 来设置文本区域的文本:

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

关于javascript - 使用 val ('' ) 清除文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45889897/

相关文章:

javascript - Google map API(使用 gmapsjs),setCenter 抛出 "undefined is not a function"?

javascript - onclick UL 标题改变?

javascript - 如何跳过测试 Nightwatch.js?

javascript - 本地系统日期格式

javascript - 使用 jQuery 获取跨度起点的偏移量

php - 恢复选择框选项,如果

javascript - div 位于表单内时的 div 单击事件

javascript - 使用 HTML 和 Javascript 读取本地纯文本文件

javascript - Jquery 未正确附加值

Javascript,如何将标签属性中的所有值放入数组中?