Search code examples
javascriptformsfrontendweb-component

Using data from form in JavaScript to save a name


I am trying to allow the user to send in their nickname, which I will then save and use later on in my JS.

const template = document.createElement('template')

template.innerHTML = `
  <div>
  <form id="createName">
    <label for="name">Write your name here:</label>
    <input type="text" id="name">

    <button id="confirm">Confirm</button>
  </form>
  </div>
`

class createName extends HTMLElement {
  constructor() {
    super()

    this.attachShadow({ mode: 'open' });
    this.shadowRoot.appendChild(template.content.cloneNode(true));

  }

  saveName() {
    let nickname = this.shadowRoot.querySelector('#name').value
    console.log(nickname)
  }

  connectedCallback() {
    this.shadowRoot.querySelector('#confirm').addEventListener('click', () => this.saveName())
  }

  
}

window.customElements.define('name-form', createName)

The form looks right in the browser, so it's something to do when I'm trying to get the actual name. Nothing is console.log-ed, so I'm thinking the saveName() is the issue. I'm unsure of how to get a hold of what the user is actually typing in.


Solution

  • Simplify your Web Component; less code means less potential errors.

    Looked to me like you fell in the FORM-auto-submit trap:

    <my-form></my-form>
    
    <script>
      customElements.define("my-form", class extends HTMLElement {
        constructor() {
          super().attachShadow({mode: 'open'}).innerHTML = `
          <form>
            <label for="name">Write your name here:</label>
            <input type="text" id="name">
            <button>Confirm</button>
          </form>`;
          this.shadowRoot.querySelector("button").onclick= (evt) => {
            evt.preventDefault(); // prevent FORM submit
            let nickname = this.shadowRoot.querySelector('input').value;
            document.body.append("You said:" , nickname);
          }
        }
      });
    </script>