Selecting an element ID that was created in an innerHTML variable

48 Views Asked by At

How do I select the textfield element "member-name"?

function revealPaywall (){
  const paywall = document.getElementById('paywall')
  const name = localStorage.getItem("value");
//TO WRITE MULTILINE HTML IN JS, USE BACKTICKS `` TO CREATE A TEMPLATE LITERAL
  if (localStorage.getItem("value") === null){
    paywall.innerHTML =
      `
      <h1>This Is An Example Of A Paywall<h1>
      <p>If you enter a name, it will be saved to the localStorage. To bypass just enter your name and click the "submit" button<p>
        <label for="name">Member Name:</label>
        <input type="text" id="member-name">
        <br><br><br>
        <button onclick="paywallComplete()">SUBMIT</button>
      `
  }
}
function paywallComplete (){
  const paywallName = document.querySelector("#member-name");
  if (paywallName.value === null){
    window.alert('hi');
  }

Am I selecting it correctly? if so why am I not getting a 'hi' alert when clicking on the submit button. I press it with the textfield empty so I'm assuming the paywallName.value === null should be true. I tried querySelector(#member-name) & querySelector(member-name) to no avail.

2

There are 2 best solutions below

0
Muhammed Eyüp Yılmaz On BEST ANSWER

In JavaScript, when an input field is empty, its value is not null, but an empty string (""). So, when you check paywallName.value === null, it won't be true for an empty input field.

function paywallComplete() {
  const paywallName = document.querySelector("#member-name");
  if (paywallName.value === "") {
    window.alert('hi');
  }
}
0
AHDZ On

Why don't you add elements with DOM object? For example, in order to add the input element, add this code:

var input = document.createElement('input');
input.type = "text";
input.id = "member-name";
paywall.appendChild(input);

Also you can summarize these codes by jquery.