html <textarea>没有使用Jquery </textarea>正确重置

时间:2014-04-16 12:58:51

标签: javascript jquery html css

我有一个简单的评论表单,其中包含名称的文本字段和评论的textarea以及用于提交的常规按钮。提交按钮根据下面的jquery重置textarea。它工作正常,除了一个烦人的问题,如果我写东西并按回车它删除textarea中的文本但在textarea中创建一个新行。我如何修复它,以便在输入时textarea真的是空的?

它也在codepen上: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();
    });
});
如果问题不清楚或缺乏信息,我会道歉。提前谢谢!

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

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