Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Selecting an element ID that was created in an innerHTML variable

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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');
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading