如何使用<label> <input> <button>在<input>中启用自动完成功能

时间:2019-07-09 04:38:58

标签: javascript html

我不是Web开发人员,但是我有一项任务要为输入框添加自动完成功能。请把我当作一个初学者。

<div>
  <label id="email_label" for="send_email" style="padding-right:5px">
    Send Email:
  </label>
  <input id="send_email" type="text" placeholder="e.g. xx.yy@zz.com" />
  <button id="ack" onclick="requestAck()">
    Request
  </button>
</div>

requestAck()是一种JavaScript函数,用于向用户指定的地址(即<input >中的地址)发送电子邮件。我正在尝试在<input autocomplete="on" ...>中添加一个标志,但是它不起作用。也许是因为它不在<form></form>环境中。

能否帮助我修改此代码,以添加自动完成功能(来自缓存),而无需更改其他功能。非常感谢!

2 个答案:

答案 0 :(得分:1)

尝试在输入标签上设置属性name="email",如果没有设置该属性,浏览器将不知道应该使用什么来自动完成该字段:)

提示:我热烈建议您将输入的类型设置为使用type="email"而不是文本的电子邮件,这不是必需的,但是它将有助于验证输入!

检查此代码:

        <div>
            <label id="email_label" for="send_email" style="paddingright:5px">Send Email:</label>
            <input id="send_email" type="email" name="email" placeholder="e.g. xx.yy@zz.com" />
            <button id="ack" onclick="requestAck()">Request</button>
        </div>

编辑:评论中讨论的最终解决方案

<form onsubmit="submitForm(event)">
  <label id="email_label" for="send_email" style="padding-right:5px">Send Email:</label>
  <input id="send_email" type="email" autocomplete="email" name="email" placeholder="e.g. xx.yy@zz.com" />
  <button id="ack" type="submit">Request</button>
</form>
<script>
  function submitForm(e) {
    e.preventDefault(); // this prevents the page from reloading
    requestAck();
  }

  //dummy function so the javascript won't crash:
  function requestAck() {}
</script>

工作示例:https://codesandbox.io/s/focused-cray-ubkw4

答案 1 :(得分:0)

您可以将autocomplete属性用于输入字段。 More info

<input autocomplete="on|off">
相关问题