skip to Main Content

If I invoke greeting() on page load then I receive nothing in the browser (I am looking to amend h1 accordingly). I have tried console.log on various points and my conclusion is that since I am invoking greeting() upon page load, the userInput() is still an empty string when inputValidator() needs it.

I don’t want an event listener such as okBtn.addEventListener("click", () => {*some code here*} in the main code body because when I am doing so, the {*some code here*} runs every time I click on okBtn , and I have some other functionalities as well which I would like to associate with this button’s click. Also I would like all my messages to appear in the same h1 and I would prefer not to include additional elements for the above. Thanks

A little side note: upon reloading the page, I get the input (cached data) from before refreshing the page appearing in the browser console when I use console log. Just for my knowledge, is there a way to clear the browser cache upon page reload?

I tried window.location.reload(); but

  1. This doesn’t seem to work in Google Chrome and works only in Fire Fox

  2. I am using VS Code Live Server and using this command keeps refreshing my page as it is probably meant to do.

var nameInput = document.getElementById("input");
var questions = document.getElementById("name-move");
var okBtn = document.getElementById("ok-btn");

window.onload = function() {
  document.querySelector("form").reset();
  questions.innerHTML = `Please enter your first name!`;
};

let userInput = () => {
  return nameInput.value;
};

let inputValidator = (val) => {
  okBtn.addEventListener("click", () => {
    if (val.length > 15 || /[0-9.*+?><,#^=!:${}()|[]/\]+/g.test(val)) {
      questions.innerHTML = `No numbers or special characters and no more than 15 characters allowed`;
    } else {
      return val;
    }
  });
};

function greeting() {
  let us = inputValidator(userInput());
  questions.innerHTML = `Welcome ${us}! Let's play Rock Paper and Scissors!`;
}
<h1 id="name-move"></h1>
<form action='#'>
  <input type="text" placeholder="Type here..." id="input" required>
  <button id="ok-btn">OK</button>
</form>

2

Answers


  1. Chosen as BEST ANSWER

    Thank you very much All! I have got it working with all your help actually. So it needed preventDefault() which I had missing. I also took on board another advice to move my logics. Current JavaScript is below. It might still become fickle upon introducing further functionalities but so far so good ;)

    let inputValidator = (val) => {
      val = nameInput.value;
      if (val.length > 15 || /[0-9.*+?><,#^=!:${}()|[]/\]+/g.test(val)) {
        return `No numbers or special characters and no more than 15 characters allowed`;
      } else {
        console.log(val);
        return val;
      }
    };
    
    function greeting() {
      questions.innerHTML = `Hi ${inputValidator()}`
    }
    
    let clickStart = () => {
      okBtn.addEventListener("click", e => {
        e.preventDefault();
        greeting();
      });
    };
    clickStart();
    

    1. You can removeEventListener from the button whenever you want to.
    2. You can add as many event listeners as you want to the button’s click

    now you can just add your event listeners and remove them when required.
    this code is a sample, you probably would move the removeEventListener part to the validator to prevent unsubscribing unless welcome message was shown first.

    You can see only the second event listener will run after you unsubscribe from the first listener.

    I added preventDefault to prevent the form from submitting.

    you can add other listeners to the same button after the welcome message to simulate steps, at each step you remove previous listener and add a new one.

    var nameInput = document.getElementById("input");
    var questions = document.getElementById("name-move");
    var okBtn = document.getElementById("ok-btn");
    
    window.onload = function () {
      document.querySelector("form").reset();
      questions.innerHTML = `Please enter your first name!`;
    }
    
    const validateInputValue = () => {
       const val = nameInput.value
       if (val.length > 15 || /[0-9.*+?><,#^=!:${}()|[]/\]+/g.test(val)) {
          questions.innerHTML = `No numbers or special characters and no more than 15 characters allowed`;
        } else { 
           return val;
        }
    }
    
    const updateHeading = () => {
        console.log('running click event')
        event.preventDefault()
        questions.textContent = validateInputValue()
        okBtn.removeEventListener('click', updateHeading)
    }
    
    const stopEvent = () => {
        console.log('Stopping submit')
        event.preventDefault()
        event.stopPropagation()
    }
    
    okBtn.addEventListener('click', updateHeading)
    okBtn.addEventListener('click', stopEvent)
    <h1 id="name-move"></h1>
    <form action ='#'>
      <input type="text" placeholder="Type here..." id="input" required>
      <button id="ok-btn">OK</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search