首页 > 解决方案 > 为什么我的“向表中添加行”功能不起作用?

问题描述

我正在尝试创建一个函数,该函数在每次提交表单时向表中添加新行和值:

预约HTML页面:

<div class="contact-form">
    <form action="https://formspree.io/MYEMAIL" id="book_appt" 
     method="POST">

        <label>Name: </label><input id="customerName" class ="form-control" 
        type="text" name="Name of Customer" required></input>

        </br>
        <label>Email Address: </label><input id="customerEmail" class="form- 
        control" type="email" name="Email Address" required></input>
        </br>

        <label>Phone no.: </label><input id="customerPhone" class ="form- 
        control" type="number" name="Phone No." required></input>
        </br>
        <label>Date & Time of Test Drive: </label><input id="customerDate" 
         class ="form-control" type="datetime-local" name="Date & Time of 
         Test Drive" required></input>

        <input type="submit" value="Submit" onclick="addData()">

    </form>
    </div>

预约表html页面:

    <table id="tblAppts" style="width:60%; border: 1px solid black" 
border="1" 
align="center">

<thead>
<tr>
<th>Name</th>
<th>Email</th> 
<th>Phone Number</th>
<th>Date/Time of Appt</th>
</tr>
</thead>

<tbody>

<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>

</tbody>
</table>

Javascript:

function addData() {

var name = document.getElementById("customerName").value;
var email = document.getElementById("customerEmail").value;
var phone = document.getElementById("customerPhone").value;
var date = document.getElementById("customerDate").value;

var tableRef = 
document.getElementById('tblAppts').getElementsByTagName('tbody')[0];

var newRow   = tableRef.insertRow(tableRef.rows.length);

var nameCell  = newRow.insertCell(0);
var emailCell  = newRow.insertCell(1);
var phoneCell  = newRow.insertCell(2);
var dateCell  = newRow.insertCell(3);

nameCell.innerHTML = name;
emailCell.innerHTML = email;
phoneCell.innerHTML = phone;
dateCell.innerHTML = date;

var newText  = document.createTextNode('New row');
}

当我单击 appt 预订页面上的提交按钮时,我会收到一封默认电子邮件(我没有附加此功能,因为它可能不相关),但我希望它也执行 addData(),但事实并非如此。谁能看到问题可能是什么?

标签: javascripthtml

解决方案


To test if your addData function is working, change the input type of 'submit' to 'button'. If everything is right then it should work fine.

The reason you are not able to see the result of addData function call is because it is attached to an onclick handler of a submit input button. It causes the form to submit and take you to new URL.

If I understand correctly what you are trying to do, there are two ways you can go about:

  • You can try to submit the form as an AJAX request(Send information without changing the page url) and not the way you are currently doing. When the request is successful you can call your addData() function.
  • Or your submission can create a new row entry in your backend database (assuming you have one) while also triggering a page refresh. This page, when loading, should populate the entries that are there in the backend database.

推荐阅读