form表单提交时自动清空表单内容
<form>
<div class="input-div">
<label for="username">用户名</label>
<input type="text" id="username" name="username">
</div>
<div class="input-div">
<label for="password">密码</label>
<input type="password" id="password" name="password">
</div>
<div class="input-div">
<label for="okpassword">确认密码</label>
<input type="password" id="okpassword" name="okpassword">
</div>
<div class="input-div">
<label for="address">所在地</label>
<input type="text" id="address" name="address">
</div>
<div class="input-div">
<label for="tel">电话</label>
<input type="text" id="tel" name="tel">
<button style="position: relative;" onclick="sendCode()">发送</button>
</div>
<div class="input-div">
<label for="code">验证码</label>
<input type="text" id="code" name="code" >
</div>
<button onclick="register()">注册</button>
</form>
这一部分
<div class="input-div">
<label for="tel">电话</label>
<input type="text" id="tel" name="tel">
<button style="position: relative;" onclick="sendCode()">发送</button>
</div>
此时只要点击提交按钮就会发现表单数据会被直接清空,这是因为form中的button默认为submit,默认会被解读为提交表单,而我这里只是想发个验证码。
解决方案
-
把button标签换成a标签,这样就可以了;
-
是由于form表单中,button的type属性默认是submit,当type的值是submit时,点击button就会自动刷新。手动设置type字段的值就解决了,即type=“button”.(推荐)
<div class="input-div">
<label for="tel">电话</label>
<input type="text" id="tel" name="tel">
<button type="button" style="position: relative;" onclick="sendCode()">发送</button>
</div>