简体   繁体   中英

Chrome Extension HTML Setting Focus to Input Field After Submitting

This is a chrome extension and I am trying to get the focus to return to the text box input after submitting.

Basically, I want the input process to be as follows: 1. User types input in 2. User presses enter or clicks the button 3. Form submits, doesn't refresh, resets itself, and retains focus so the user can easily add more inputs.

If the user presses enter, the focus is retained. However, as soon as the user presses the button (add website), the text box input loses focus. I'm not sure why the following HTML and corresponding JavaScript don't work:

<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="popup.js"></script>
    <title>Add a website to block</title>
  </head>
  <body>
    <form id="addWebsiteForm">
    Website Address: <input type="text" id="websiteAddress"><br>
    <input type="submit" value="Add Website">
    </form>
  </body>
</html>

JavaScript:

var addWebsiteForm;

document.addEventListener('DOMContentLoaded', function(){
  addWebsiteForm = document.getElementById("addWebsiteForm");
  addWebsiteForm.addEventListener('submit', addWebsite);
});

function addWebsite(event) {
  addWebsiteForm.focus();
  event.preventDefault();
  var websiteAddress = document.getElementById("websiteAddress").value;
  var storedWebsites;

  chrome.storage.local.get('websites', function(objects) {

    if (!objects.websites) {
        storedWebsites = [];
    } else {
        storedWebsites = objects.websites;
    }

    storedWebsites.push(websiteAddress);
    chrome.storage.local.set({'websites':storedWebsites});
    addWebsiteForm.reset();
  });
}

You've actually only made one small error. You're focusing on the whole form instead of the input field. In the top of your JavaScript create another line with the input text's id. Then set focus to that one after resetting the form.

Like this,

websiteAddress = document.getElementById("websiteAddress");

websiteAddress.focus();

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