Is there a way to utilize a parameter for the user's input instead of relying on document.getElementById when incorporating a button?

let totalScore = 0;
var myArray = [1, 2, 3, 4, 5];

let randomNum;

function NumGuess(userInput) {

  var userGuess = userInput;

  var i;
  for (i = 0; i < 1; i++) {
    var randomNum = myArray[Math.floor(Math.random() * myArray.length)];
  }

  if (userGuess == randomNum) {
    alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
    totalScore++;
  } else {
    alert("SORRY, The correct number was " + randomNum);
    totalScore = totalScore - 1;
  }
  document.getElementById("GameScore").innerHTML = "Score: " + totalScore;
}
<!doctype HTML>
<html>
  <body>
    <p id="GameScore">Score: 0</p>
    <button onclick="NumGuess(document.getElementById('userInput').value)">Start Game!</button>
    <input id="userInput" type="text">
  </body>
</html>

Trying to pass the user input as a parameter in the function instead of defining it within the function. However, faced with a challenge since user input is coming from a textbox triggered by a button click.

Answer №1

  1. To properly handle user input, it is best to pass the value of the input to the function.
  2. It is recommended to use `addEventListener` instead of inline event handlers for better code organization and maintainability.

let score = 0;
var myArray = [1, 2, 3, 4, 5];

function GuessNumber(userGuess) {
  var i;
  for (i = 0; i < 1; i++) {
    var randomNumber = myArray[Math.floor(Math.random() * myArray.length)];
  }
  if (userGuess == randomNumber) {
    alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
    score++;
  } else {
    alert("SORRY, The correct number was " + randomNumber);
    score = score - 1;
  }
  document.getElementById("GameScore").innerHTML = "Score: " + score;
}
document.querySelector('button').addEventListener('click', e=>{
  GuessNumber(document.getElementById("userInput").value);
});
<!doctype HTML>
<html>
  <body>
    <p id="GameScore">Score: 0</p>
    <button>Start Game!</button>
    <input id="userInput" type="text">
  </body>
</html>

Answer №2

Do you have something in mind that resembles this?

<!doctype HTML>
<html>
  <body>
    <p id="GameScore">Score: 0</p>
    <button onclick="GuessNumber(document.getElementById('userInput').value)">Start Game!</button>
    <input id="userInput" type="text">
  </body>
</html>
let score = 0;
var myArray = [2, 3];

let randomNumber;

function GuessNumber(userGuess) {

  var i;
  for (i = 0; i < 1; i++) {
    var randomNumber = myArray[Math.floor(Math.random() * myArray.length)];
  }

  if (userGuess == randomNumber) {
    alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
    score++;
  } else {
    alert("SORRY, The correct number was " + randomNumber);
    score = score - 1;
  }
  document.getElementById("GameScore").innerHTML = "Score: " + score;
}

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

PHP script is not successfully receiving the Ajax post request that is

As a newcomer to the world of php and ajax, I am facing a challenge in passing a variable from jquery to a php page loaded within a modal window. My php script fetches table information for multiple users. Next to each user's name, there is an edit b ...

Using AJAX within the $.when function to extract the first character from the returned string

Currently, I am utilizing an AJAX call by using $.when to wait for the completion of that specific ajax request and then continue with processing the subsequent ajax request inside. The code block below demonstrates where the $.when method is being invoke ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

Utilizing numerous X-axis data points in highcharts

I'm working with a line graph that dips straight down, like starting at (1, 100) and dropping to (1,0). The issue I'm facing is that Highcharts () only displays information for one of the points. Is there a way to make it show information for bot ...

Struggling to populate a nested array in a dropdown using AngularJS

I am currently working on populating JSON data into a dropdown list, specifically focusing on main category, sub category and sub sub category. Successfully managed to populate the main category and sub category, but facing challenges with populating subsu ...

"By setting the HTML input box to read-only, the JavaScript button has the

Check out this js fiddle demonstration: http://jsfiddle.net/YD6PL/110/ Here is the HTML code snippet: <input type="text" value="a" readonly> <input type="text"> <input type="text"> <div> <button class="buttons">c</button ...

How can I extract the value from the object returned by an AJAX call?

HTML file <div class="container"> <table id="headerTable" class="table table-bordered"> <thead> <tr> <th colspan="2">Header</th> </tr> </thead> <tbody> <c:forEach item ...

Guide to implementing if else statements with Protractor

I am facing some unusual situations and I'm not quite sure how to address them. As a newcomer to testing, I've been tasked with testing a website's cart function for proper functionality. The challenge arises when we add a certain number o ...

I am eager to display this JSON data using AngularJS tables

I have JSON file with content about categories, departments, and digital marketing: { "categories":[ { "dept_id":"123", "category_name":"database", "category_discription":"list of database", "current time ...

Exploring the World of Three.js Loaders

I downloaded the file package three.js-dev from threejs.org and I am trying to use it in my project like this: <script type="text/javascript" src="./build/three.js"></script> <script type="text/javascript" src="./src/loaders/JSONLoader.js" ...

Finding the x and y coordinates of a rotated 3D cube using JavaScript

In my quest to create a 3D cube using separate div elements, I am faced with a challenge. Imagine a cube made up of 3*3*3 divs where each div has: X, Y, Z coordinates in the 3D space Rotation angles around the X and Y axes With this information, I shoul ...

How to implement a "callWhenReady" function in JavaScript

I am new to javascript and currently working on restructuring my prototype code. The current setup involves multiple levels of nested callbacks, making it difficult to read and manage. I am aiming for a cleaner approach similar to the following: GoogleMap ...

Is there a way to conceal the headers during an ajax request?

I'm currently exploring APIs using jQuery and Ajax. To set the header of Ajax, I typically use code similar to this: headers: { "My-First-Header":"first value", "My-Second-Header":"second value" }, I am working on a basic school project and ...

Angular 2 eliminates the need for nesting subscriptions

Is there a way to streamline nested subscriptions like the code snippet below? I want to extract values from the subscription for better organization, but using a global variable won't work because the subscription hasn't received the value yet. ...

Modifying one input can impact other input elements without any form of direct connection between them

Below is the HTML code snippet: <tr *ngFor="let row of formData; let i = index" [attr.data-index]="i"> <td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j"> <input type="checkbox" name="row-{{i}}-{{j}}" [ ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Ways to attach the close event to the jquery script

Hello, I'm having trouble reloading the parent page when the close button is clicked on a modal dialog. Here's my code snippet: //customer edit start $( ".modal-customeredit" ).click(function() { var myGroupId = $(this).attr('data- ...

Unable to successfully add element to array using UIKit modal in vuejs

On my webpage, I have a table that showcases an array of "currency" objects: <tbody> <tr v-for="currency in currencies" v-bind:key="currency.Name"> <td class="uk-width-medium">{{currency.Enabled}}</ ...

What strategies can be used to refactor nested callbacks in node and effectively pass parameters to each function within the callbacks?

I am currently in the process of refactoring some JavaScript code within a Node environment, and I'm encountering difficulties when it comes to passing parameters to functions that serve as callbacks for other functions. Here is an example of my curre ...

Issue: TableHead inside an Expandable Row in MUI-Datatable is being duplicated for each row, causing the table to not be centered.Explanation: The

Can anyone help me with this issue? I'm having trouble with my table where the headings are repeating for every row and the table is stuck on the far right side. How can I center the table instead? https://i.sstatic.net/y7Cs5.png Codesandbox: https: ...