为什么不起作用?尝试使用隐藏的提交按钮添加行

时间:2015-11-21 02:53:23

标签: javascript jquery

我正在尝试使用输入按钮作为提交来制作一个简单的Todo列表。这会将输入的内容添加到它下面的列表中。我觉得我错过了一些东西,因为它不适合我。隐藏我的按钮以尝试使页面更清洁。谢谢!

$(document).ready(function() {
 $("#hiddenEnterBtn").on("click", function() {

   var newTodo, newRow, newTd;

   newTodo = $("#inputField").val();
   newRow = $("<tr>");
   newTd = $("<td>").addclass("undone").append(newTodo);
   newRow.append(newTd);

   $("tbody").append(newRow);

 });
});

   <table class="table">
      <thead>
        <th>Things that should get done...like yeah get on that</th>
      </thead>
      <tbody>
        <tr>
          <td>
            <form>
              <input type="text" id="inputField" class="form-control" autocomplete="off" placeholder="What I need to do" />
              <button type="submit" id="hiddenEnterBtn"></button>
            </form>
          </td>
        </tr>
      </tbody>
    </table>

3 个答案:

答案 0 :(得分:0)

与此JS Fiddle一样,您需要先阻止提交按钮的默认行为,然后根据需要执行工作

&#13;
&#13;
$(document).ready(function() {
 $(".table form").on("submit", function(e) {
     e.preventDefault();

   var newTodo, newHtml;

   newTodo = $("#inputField").val();
   newHtml = '<tr><td class="undone">' + newTodo + '</td></tr>';

   $("tbody").append(newHtml);

 });
});
&#13;
#hiddenEnterBtn{
    visibility:hidden;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table class="table">
      <thead>
        <th>Things that should get done...like yeah get on that</th>
      </thead>
      <tbody>
        <tr>
          <td>
            <form>
              <input type="text" id="inputField" class="form-control" autocomplete="off" placeholder="What I need to do" />
              <button type="submit" id="hiddenEnterBtn"></button>
            </form>
          </td>
        </tr>
      </tbody>
    </table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要在点击事件的开头添加event.preventDefault()以防止被发送。所以你的代码应该是:

$("#hiddenEnterBtn").on("click", function(event) {
   event.preventDefault();

   var newTodo, newRow, newTd;

   newTodo = $("#inputField").val();
   newRow = $("<tr>");
   newTd = $("<td>").addclass("undone").append(newTodo);
   newRow.append(newTd);

   $("tbody").append(newRow);

});

答案 2 :(得分:0)

这是一个适合你的JS小提琴。

https://jsfiddle.net/0267stfq/1/

    <table class="table">
  <thead>
    <th>Things that should get done...like yeah get on that</th>
  </thead>
  <tbody>
    <tr>
      <td>
        <form method="POST" onsubmit="return false;">
          <input type="text"mautocomplete="off" placeholder="What I need to do" />
          <button></button>
        </form>
      </td>
    </tr>
  </tbody>
</table>

JS:

 $(document).ready(function() {
$("button").on("click", function() {
     var newTodo = $("input").val();
     $('.table tbody tr:last').after('<tr> <td>' + newTodo + '</td> </tr>');
 });
});