我在右上角做了一个添加按钮(见第一个截图),当我点击它时,它会显示一个表单,其中有 3 个输入字段用于添加姓名、联系电话、组名和最后的提交按钮。
我在表单的 input
字段中添加了 required
属性,但是当我点击提交按钮时它不起作用,它提交了空白的详细信息(见第二张截图)
在 app.js 中:
我正在使用 javascript 动态添加 HTML:
<div class="row">
<div class="col-lg-12" id="addNewContact">
<form>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="nameInput">
</div>
<div class="form-group">
<label for="number">Number:</label>
<input type="text" class="form-control" id="numberInput">
</div>
<div class="form-group">
<label for="group">Group:</label>
<input type="text" class="form-control" id="groupInput">
</div>
<button type="button" class="btn btn-success" onclick="submitToDb()">Submit</button>
</form>
</div>
</div>
截图:
显示空白字段见截图:
最佳答案
不要使用 onclick
,而是在表单上使用 onsubmit
。
<form onsubmit="submitToDb()">
表单验证在处理 submit
事件时完成。如果您使用单击按钮提交表单,则会在默认提交发生之前发生。
关于javascript - 表单未使用 javascript 进行验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48690569/