简体   繁体   中英

How to enable autocomplete in <input > with <label ><input ><button >

I am not web developer, but I have a task to add autocomplete function for an input box. Please treat me as a very beginner.

<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() is a javascript function sending a email to address given by user (ie address in <input > ). I am trying to add a flag in <input autocomplete="on" ...> , but it doesn't work. Perhaps because it's not in a <form></form> environment.

Could you help me to modify this code adding autocomplete (from cache) without changing other functions. Many thanks!

Try setting the property name="email" on the input tag, without that set the browser doesn't know what's supposed to autocomplete the field with :)

protip : I warmly suggest you to set the type of the input to email with type="email" instead of text, it's not required but it will help validating the input!

check this code:

        <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>

EDIT: Final solution discussed in comments

<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>

Working example: https://codesandbox.io/s/focused-cray-ubkw4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM