Display the input provided after submission to ensure that it is visible

Currently, I am working on a rock, paper, and scissors exercise where I've included a form with input text and a button to store the user's name and display it on the DOM.

The issue arises when trying to access the value in the console using $userName.value. It only shows the value when it's in the input box; once deleted or submitted, it displays nothing or undefined. My intention is to have the user send the text from the input and then clear the input field. Even setting the .value to an empty string didn't work as expected.

I used a variable with innerHTML to display the user's name on the DOM. However, if I clear the input, it ends up showing 'undefined.'

I feel like there might be some steps that I'm missing, but I'm unsure how to approach it. Any help or guidance would be highly appreciated.

// Global DOM variables
const $selectBtn = document.querySelectorAll("[data-selector]");
const $displayUserScore = document.querySelector("#user-score");
const $displayComputerScore = document.querySelector("#computer-score")
const $showScore = document.querySelector("h5");
const $theWinnerIs = document.querySelector('#result-winner');
const $refreshBtnContainer = document.querySelector('#refresh-button-container');
const $icons = ["🪨", "🧻", "✂️"];
let $userForm = document.querySelector('#user-form');
let $userName = document.querySelector('#user-name');

// Score variables
const choices = ["rock", "paper", "scissors"];
let userScore = 0;
let computerScore = 0;

$userForm.addEventListener('submit', (event) => {
    $newUserName = $userName.value;
    $userForm.submit();
})

// Iterate through each button...
$selectBtn.forEach(function(button){
    
    button.addEventListener("click", function() {
        let computerOption = computerRandom(); // Store random computer play in a variable
        const userOption = button.dataset.selector; // userOption equals data-selector attribute
        
        // Function to play the game and determine the winner
        playGame(userOption, computerOption);
        theWinner();
        
        // Function to display results
        function playGame(userOption, computerOption) {

            if (userOption === "rock") {
                if (computerOption === "scissors") {
                    userScore++;
                    $displayUserScore.innerHTML = userScore;
                    $showScore.innerHTML = "The machine chooses "+"<span class=\"icon\">" + [...]</span>" + ", you BEAT him!";
                } else if (computerOption === "paper") {
                    computerScore++;
                    $displayComputerScore.innerHTML = computerScore;
                    $showScore.innerHTML = "The machine chooses "+"<span class=\"icon\">" + [...]</span>" + ", you LOSE!";
                } else if (userOption === computerOption) {
                    $showScore.innerHTML = "Draw!";
                }
            }

            if (userOption === "paper") {
                if (computerOption === "rock") {
                    userScore++;
                    $displayUserScore.innerHTML = userScore;
                    $showScore.innerHTML = "The machine chooses "+"<span class=\"icon\">" + [...]</span>" + ", you BEAT him!";
                } else if (computerOption === "scissors") {
                    computerScore++;
                    $displayComputerScore.innerHTML = computerScore;
                    $showScore.innerHTML = "The machine chooses "+"<span class=\"icon\">" + [...]</span>" + ", you LOSE!";
                } else if (userOption === computerOption) {
                    $showScore.innerHTML = "Draw!";
                }
            }

            if (userOption === "scissors") {
                if (computerOption === "paper") {
                    userScore++;
                    $displayUserScore.innerHTML = userScore;
                    $showScore.innerHTML = "The machine chooses "+"<span class=\"icon\">" + [...]</span>" + ", you BEAT him!";
                } else if (computerOption === "rock") {
                    computerScore++;
                    $displayComputerScore.innerHTML = computerScore;
                    $showScore.innerHTML = "The machine chooses "+"<span class=\"icon\">" + [...]</span>" + ", you LOSE!";
                } else if (userOption === computerOption) {
                    $showScore.innerHTML = "Draw!";
                }
            }

        }
        
        // Function to declare the ultimate winner
        function theWinner() {
            if (userScore === 5) {
                $theWinnerIs.innerHTML = $userName.value;
            } else if (computerScore === 5) {
                $theWinnerIs.innerHTML = "The machine!";
            }
        }

        if (userScore === 5 || computerScore === 5) {
            const $refreshBtn = document.createElement('button');
            $refreshBtn.appendChild(document.createTextNode("Play again!"));
            $refreshBtn.className = "refresh-btn";
            $refreshBtnContainer.appendChild($refreshBtn);
            let len = $selectBtn.length;

            for (let i = 0; i < len; i++) {
                $selectBtn[i].disabled = true;
            }
            
                $refreshBtn.addEventListener('click', () => {
                userScore = 0;
                computerScore = 0;
                $displayUserScore.innerHTML = userScore;
                $displayComputerScore.innerHTML = computerScore;
                $showScore.innerHTML = "";
                $theWinnerIs.innerHTML = "";
                $refreshBtnContainer.innerHTML= "";
                for (let i = 0; i < len; i++) {
                    $selectBtn[i].disabled = false;
                }
            })   
        }

    })
    
})

// Randomly select computer choice
function computerRandom () {
    const randomNumber = Math.floor(Math.random() * choices.length);
    return choices[randomNumber];
}
body {
    box-sizing: border-box;
}

#container {
    text-align: center;
    margin-top: 5%;
}

h2 {
    color:rebeccapurple;
    font-size: 30px;
    letter-spacing: 4px;
    font-style: italic;
}

#user-name {
    margin-bottom: 4em;
    border-radius: 10px;
    padding: .6em;
    outline: none;
    border: none;
}

#submit-name {
    padding: .6em;
    margin-left: .5em;
    background: rebeccapurple;
    border-radius: 10px;
    border: none;
    outline: none;
}

.btn-selector {
    font-size: 4em;
    background: rebeccapurple;
    margin: .1em;
    padding: .2em;
    outline: none;
    border: none;
    cursor: pointer;
    border-radius: 20%;
    transition: 150ms;
}
.btn-selector:hover {
    transform: scale(1.2);
}

#results {
    display: flex;
    justify-content: center;
}

.score {
    margin-right: 1em;
    font-size: 11px;
    font-style: italic;
}

h3 {
    color: rebeccapurple;
    font-style: italic;
    display: flex;
    justify-content: center;
}

h5 {
    margin-top: 7px;
    color: olive;
    font-size: 20px;
    letter-spacing: 3px;
}

.icon {
    font-size: 3em;
}

.refresh-btn {
    padding: .8em;
    background: rebeccapurple;
    font-size: 30px;
    font-style: bold;
    border-radius: 20px;
    border: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rock, paper and scissors</title>
    <link rel="stylesheet" href="style.css">
    <script src="script.js" defer></script>
</head>
<body>
    <div id="container">
        <h2>What is your name?</h2>
        <form id ="user-form">
            <input type="text" id="user-name" placeholder="Please, insert your name..">
            <input type="submit" id="submit-name" value="Enviar">
        </form>
        <button class="btn-selector" data-selector="rock">🪨</button>
        <button class="btn-selector" data-selector="paper">🧻</button>
        <button class="btn-selector" data-selector="scissors">✂️</button>
        <div id="results">
        <h4>You: <span id="user-score" class="score" data-user-score>0</span></h4>
        <h4>Computer: <span id="computer-score" class="score" data-computer-score>0</span></h4>
    </div>
    <h5></h5>
        <div>
            <h3>And the winner is...</h3>
            <h3 id="result-winner"></h3>
        </div>
        <div id="refresh-button-container">    
        </div>
    </div>
</body>
</html>

Your assistance is greatly valued.

Answer №1

Change up the variable within the function. Here, you can utilize the $userName global variable to access the HTML element and use .value to retrieve its value.

let $userForm = document.querySelector('#user-form');
let $userName = document.querySelector('#user-name');

$userForm.addEventListener('submit', (event) => {
  const nameInput = $userName.value;
  console.log(nameInput);
  $userForm.submit();
})
<form id="user-form">
  <input type="text" id="user-name" placeholder="Please enter your name..">
  <input type="submit" id="submit-name" value="Submit">
</form>

Answer №2

Uncertain if your form submission will be successful; it's hard to say for sure.

If you wish to showcase the user's name or save this information somewhere for future display, you can achieve it using the following method

HTML snippet

<form id ="user-form">
  <input type="text" id="user-name" placeholder="Please enter your name.." onchange="registerInput(this);">
  <input type="submit" id="submit-name" value="Submit">
</form>
<h1>
</h1>

JavaScript code

// Initializing a global variable
var playerUsername = ""

let $userForm = document.querySelector('#user-form');
let $userName = document.querySelector('#user-name');


function registerInput(e)
{
    const value = e.value;
    // Setting input value to playerUsername for global access
    playerUsername = value;
}

$userForm.addEventListener('submit', (event) => {
        event.preventDefault();
        // Displaying the user's name
        document.querySelector('h1').innerText = 'Hello : ' + inputValue;
        
        // Clearing the input value
        $userName.innerValue = ""

        // Success! 

})

Link : https://jsfiddle.net/k49bgu0c/6/

If you modify the .html page, the variable access may be lost; how to handle this situation?

You can store the input result in localStorage, which allows retrieval of inserted data even after page changes. Explore localStorage for more insights on its functionality.

Answer №3

Event Submission Tips

When dealing with a <form> and its association with the "submit" event, there are certain key points to keep in mind.

  • A <form> by default gathers values of form controls that are either within the form itself or linked to it via the form attribute, and have a valid name attribute (excluding buttons).
  • Upon data collection and submission to the server, a response is expected for proper user experience. Lack of a server may result in a blank page.
  • The "submit" event is triggered when a user presses the Return/Enter key on an <input> field or clicks on a submit button. Different types of submit buttons trigger the event in various ways.

If opting not to use a server, preventing the default behavior is crucial. Use event.preventDefault() as shown in Example A.

Understanding Closure

To create a closure, define a variable outside a function but within its scope. This approach ensures that the variable remains accessible even after the function has executed. Refer to Figure III for clarity.

Example A

[Code snippet demonstrating how to prevent form submission and handle data]

[Instructions on verifying the persistence of data value post-function execution]

Hidden <input> Usage

Using a hidden <input> element is another method for storing values discreetly. Such value persistence lasts until page unloading or manual reassignment of the input's value. Two types of hiding methods are highlighted:

  • Visibly Hidden <input>: Concealed from users while technically present in the layout structure.
  • display: none Hidden: Remains invisible and does not affect the layout structure.

In most cases, employing display: none for hidden inputs is recommended. See Example B for implementation.

Example B

[Code snippet showcasing the usage of hidden input fields]

Appendix

Reference guides for popular developer tools:

Firefox Developer Tools

Chrome DevTools

Edge DevTools

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

JavaScript Error: attempting to initialize an instance with an undefined function

I encountered a JavaScript error stating TypeError: undefined is not a function while attempting to instantiate a schema that I defined and imported. article.js var mongoose = require("mongoose"); var Schema = mongoose.Schema; // Article Schema var Ar ...

Another way to encode a string to base64 in Node.js without relying on the Buffer module

While utilizing Buffer in one of the cloud functions to convert a string into Base64 encoding, I have encountered a delay of 15 seconds during bulk processing. Buffer.from(JSON.stringify(msgBody)).toString('base64')) I am exploring alternative m ...

Empty results in NgRx Parameterized Selector

Having trouble implementing a parameterized query in NgRx and receiving empty results. Check out the StackBlitz version of the code here: https://stackblitz.com/edit/ngrx-parameterized-query Update to Reducer Code export const userAdapter = createEntity ...

Issue with component not updating upon state change

Having trouble getting my react function component to rerender immediately after updating the state. The application takes input for material cost of each product and calculates the total. I want the component to display the updated total as soon as the i ...

Using Three.js to control the camera's position and direction

Despite hours of searching, I have been unable to find a solution to a fundamental issue in Three.js. I know the position of the camera (my eyes), the direction the camera is facing (my eyes), and the direction my head is pointing. I need to create the cam ...

What is the alternative to $templateCache in Angular2 and how can CachedResourceLoader be utilized in its place?

While I have come across 2 similar questions on Stack Overflow and here, none of them seem to provide a solution. After delving into the Angular repository, I stumbled upon this issue where they inquire about an alternative for templateCache in Angular 2, ...

What is the most efficient way to iterate through an array and retrieve the values of each item in it?

I'm trying to iterate through an array of objects and retrieve all the data from each object, but for some reason, I'm only getting the data from the last object. Can anyone help me figure out why it's skipping the first one? Here is the arr ...

Attempting to transfer a property from one page to another using the Link component in NextJS

Currently, I have a page containing six Link elements that are meant to redirect to the same destination but with different props based on which link is clicked. To pass props, this is how I've implemented it: <Link href={{ pathname: '/pro ...

Displaying stack traces in a request using HttpInterceptor in Angular 9

I have created an HttpInterceptor and I would like to print the stack trace of the functions involved in making the request for development purposes: import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, ...

Verify whether the variable is defined or present within the Angular controller

In my Angular controller, I have the following function: $scope.sendCompanyData = function() { delete $scope.company["step1Form"]; delete $scope.company["step2Form"]; delete $scope.standard_address["state"]; $http.post(Routing.generate(&a ...

Display images in a list with a gradual fade effect as they load in Vue.js

In my Vue project, I am looking to display images one at a time with a fading effect. I have added a transition group with a fade in effect and a function that adds each image with a small delay. However, I am facing an issue where all the images show up ...

the function fails to run upon clicking the button again

Here is the current function in use: function beTruthful() { if (document.getElementById("about").style.opacity = "0") { document.getElementById("about").style.opacity = "1"; } else { document.getElementById("about").style.opacity ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

Having difficulties persisting information from freshly generated input fields with the "Add" button to the database

Currently, the issue lies with the database only accepting data from the first input field in PHP. <form class = "spendings" method ="POST" action="InsertToDatabase.php"> <div id="numbering">ITEM 1: </div> <div class="entry"> ...

Upon migrating from Vue CLI 2 to 3, an error is thrown stating: "Cannot locate element: #app" and an empty body is

Currently, I am in the process of transitioning my VueJS project from VueCLI 2 to version 3. After moving all the necessary files to the src folder, I attempted to view it in the browser by running npm run serve. However, I encountered a problem where the ...

Fill in a Symfony form field using a table row's index value

Hey there, I'm encountering a little hiccup here, but I am confident that you, the JavaScript expert, can help me out! Let's start with my Symfony form: $form = $this->createFormBuilder() ->add('accept', 'checkb ...

"Encountering issues with Instagram embeds.js library failing to load

I've been working on a JavaScript function that loads the HTML embed code for Instagram posts. When the post appears, the photo is replaced by a grey background and the Instagram logo. Even though the post contains other information like hashtags, tim ...

The appearance of the image is distorted once it is inserted into the carousel

I am currently working on a carousel that contains 5 images with varying heights and widths. However, I am experiencing some issues with the way the images are displayed - some are stretched while others are centered within the carousel. My goal is to ens ...

A solitary outcome yielded by the JSON iteration

Can anyone help me understand why this code is only returning 1 result instead of 4? I am trying to retrieve all the post titles in the category with ID 121, but it seems to only display the most recent post title. <script type="text/javascript> ...