form表单提交时自动清空表单内容

文章讲述了在HTML表单中,使用button默认的submit类型会导致表单提交时内容被清空的问题。解决方法是将button的type属性改为button,以实现仅触发验证码发送功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,默认会被解读为提交表单,而我这里只是想发个验证码。

解决方案

  1. 把button标签换成a标签,这样就可以了;

  2. 是由于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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值