html<text区域>未使用Jquery正确重置

html <textarea> not resetting properly using Jquery

本文关键字:Jquery gt lt text 区域 html 未使用      更新时间:2023-09-26

我有一个简单的注释表单,它由一个用于名称的文本字段、一个用于注释的文本区域和一个用于提交的常规按钮组成。提交按钮根据下面的jquery重置文本区域。它工作得很好,除了一个令人讨厌的问题,如果我写了一些东西并按enter键,它会从文本区域删除文本,但会在文本区域创建一行新行。如何修复它,使文本区域在按enter键时真正为空?

它也在代码笔上:http://codepen.io/erikL/pen/Leymj

HTML

<p class="inline-block name">Name</p>&nbsp
<input type="text" placeholder="Your name" id="userName" maxlength="30">
    <textarea class="comment" id="userComment" placeholder="Enter your comment here" maxLength="300"></textarea>
    <p><em>max 300 characters</em></p>
    <input type="button" class="comment" value="Submit" onclick="userComment()" id="button" />
<div id="comments"></div>

用于提交评论的Javascript

function userComment() {
  var textd = document.getElementById("userComment");
  var named = document.getElementById("userName");
  var textdVal = textd.value;
  var namedVal = named.value;
  if (namedVal.length < 1) {
    alert('Please enter you name.');
  }
  else {
    if(textdVal.length < 3) {
      textdVal = 'No comment.';
    }
  var namedParagraph = document.createElement('p');
  var textdParagraph = document.createElement('p');
  namedParagraph.textContent = namedVal + (' - ') + date;
  textdParagraph.textContent = textdVal;
  namedParagraph.className = 'commentName';
  textdParagraph.className = 'commentText';
  document.getElementById("comments").appendChild(namedParagraph);
  document.getElementById("comments").appendChild(textdParagraph);
  document.getElementById("userName").value=""; //this is where it resets the name
  document.getElementById("userComment").value=""; //this is where it resets the comment
  }
};

Jquery用于重置表单

$(document).ready(function(){
    $('#userComment').keypress(function(e){
      if(e.keyCode==13) 
      $('#button').click();
    });
});

如果问题不清楚或缺乏信息,我深表歉意。提前感谢!

e.preventDefault()添加到keypress处理程序的条件中。

http://codepen.io/anon/pen/Avzaq

这是解决方案。。。e.preventDefault();

$(document).ready(function(){
   $('#userComment').keypress(function(e){
     e.preventDefault();
     if(e.keyCode==13) 
     $('#button').click();
  });
});