skip to Main Content

I’m writing a script to take input from the user and greet him

But nothing happens on the page. There is an input form which takes an input and submits it. That’s it. It doesn’t print anything then.

What I’m doing wrong? How can I fix it?

I expect the code to print something like "Hello, Sam" where Sam is the user’s input.

<form>
   <input type="text" id="firstName" name="firstName" />
   <button type="submit">Submit</button>
</form>

<script>
   let inp = document.getElementById("firstName").value;
   console.log("Hello, " + inp);
</script>

3

Answers


    1. You need to not submit the form or you will reload the page
    2. You are using console.log to show the result, so you need to look in the console for the text. Press F12 or right-click and inspect and look in the console tab
    3. You are not actually doing anything with the code that is related to the form submit event – your script is just running with what is in the form at load time

    Using a submit event listener, you can do this – I am using template literal to format the text:

    document.getElementById("nameForm").addEventListener("submit", (e) => {
      e.preventDefault(); // we cancel the submit event
      let firstName = document.getElementById("firstName").value;
      document.getElementById("output").innerHTML = `Hello <b>${firstName}</b>`;
    });  
    <form id="nameForm">
       <input type="text" id="firstName" name="firstName" />
       <button type="submit">Submit</button>
    </form>
    <div id="output"></div>
    Login or Signup to reply.
  1. You should create .onsubmit event for that form, so when the submit button clicks, do your task in the callback function. Don’t forget to do return false if you want to disable redirect after submission.

    If you want the simple answer, here it is:

    <form id="form" action="#">
       <input type="text" id="firstName" name="firstName" />
       <button type="submit">Submit</button>
    </form>
    
    <script>
       let form = document.getElementById('form');
       form.onsubmit = function(event) {
         let data = event.target.elements;
         let inp = data.firstName.value;
         console.log("Hello, " + inp);
         return false;
       }
    </script>
    Login or Signup to reply.
  2. <input id="firstName" type="text">
    <button onclick="submit()">Submit</button>
    
    <script>
      function submit() {
        let inp = document.getElementById("firstName").value;
        console.log('Hello, ' + inp);
      }
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search