skip to Main Content

I have a wep app that has an autocomplete feature that being triggered when the user insert’s a few specifhic words.

I would like to know how can I create a checkbox using HTML that will enable and disable the autocomplete.

Thanks,
Shoam

I was trying to find a way to do that but did not found a way, even tho I knlw it should not be too complex.

2

Answers


  1. If the checkbox is checked, it will have set the autocomplete attribute of the input element with the autocomplete="off" attribute to on. If the checkbox is unchecked, it will have set the autocomplete attribute to off.

    const autocompleteCheckbox = document.getElementById("autocomplete");
    
    autocompleteCheckbox.addEventListener("change", function() {
      const usernameInput = document.getElementById("username");
    
      if (autocompleteCheckbox.checked) {
        usernameInput.setAttribute("autocomplete", "on");
      } else {
        usernameInput.setAttribute("autocomplete", "off");
      }
    });
    <input type="text" id="username" autocomplete="off" />
    <input type="checkbox" id="autocomplete" />
    <label for="autocomplete">Enable Autocomplete</label>
    Login or Signup to reply.
  2. Set the autocomplete attribute on the input on the change event for the checkbox using event.target.checked:

    document.querySelector('#autocomplete').addEventListener('change', event => 
        document.querySelector('#username').setAttribute('autocomplete', event.target.checked ? 'on' : 'off')
        + console.log(document.querySelector('#username'))
    );
    <input id="username" autocomplete="off" />
    <label><input type="checkbox" id="autocomplete" /> autocomplete</label>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search