-1

I want to create a simple HTML document that contains label, textbox and button. When the user enters name and presses Go Navigate to another page that says Welcome {User Name} IF the name is empty display an alert that says “please enter your name”.

I can't move to the second page with the name user entered.

file1 HTML

     <h2> Enter your name.</h2><br>

  <input id="name">

    <button onclick="action()">GO</button>

     <script src="action.js">

       </scipt>

file js

    function action() {

          var PersonName = document.getElementById('name').value;
          if (PersonName== "") {
        alert("please enter your name!");
       return false;

                }

    else{


            document.location.href = "index2.html";
      }}
sao
  • 1,835
  • 6
  • 21
  • 40
codiins
  • 9
  • 5
  • 1
    Through the use of [Cookies](https://www.w3schools.com/js/js_cookies.asp) Or [Local Storage](https://www.w3schools.com/jsref/prop_win_localstorage.asp) – Zak Oct 10 '19 at 22:17
  • 2
    @codiins check this https://stackoverflow.com/questions/27765666/passing-variable-through-javascript-from-one-html-page-to-another-page – anehme Oct 10 '19 at 22:20

1 Answers1

0

A couple methods could include use of local storage or passing the username through the a URL parameter.

Method 1: Local Storage

// Set the local storage variable
localStorage.setItem('username', 'example');

//Check if the local storage variable exists
if(localStorage.getItem('username') == null) {
    // Tell the user to enter a username
}

Method 2: URL parameter I wouldn't recommend this method just because storing it in local storage is both easier and more efficient.

So when the user enters their username, you could have it send them to "index2.html?username=example". You could then get the URL parameter and use it

var url = new URL(window.location.href);

var search_params = new URLSearchParams(url.search); 

if(search_params.has('username')) {
    var username = search_params.get('username');

    // The variable username contains whatever is after the "?username=" in the URL
    console.log(username)
}
SamNewton
  • 72
  • 5