With a simple click of a button, I aim to have the ability to set a variable to true

I am looking to create a button that changes to true in the Script section. This will allow for a random number to be displayed in the paragraph element.


<!doctype html>
<html>
<button id="button">
random number
</button>
<p id="randomnumber">

</p>



</html>
<script>
var randomNumber;
document.getElementById('button').addEventListener('click', function() {
  randomNumber = (Math.floor(Math.random()*21)+2);
  document.getElementById("randomnumber").innerHTML = randomNumber;
});




</script>

Edit: I am also interested in learning how to assign the random number to a variable so I can utilize it elsewhere.

Answer №1

Hey Jeremy, give this code a shot!

<!doctype html>
<html>
<button id="button">
generate random number
</button>
<p id="randomnumber">

</p>



</html>
<script>
  document.getElementById('button').addEventListener('click', function() {
    document.getElementById("randomnumber").innerHTML = (Math.floor(Math.random() * 21) + 2);
  })
</script>

Answer №2

Perhaps you are seeking out element.addEventListener()

document.getElementById('btn').addEventListener('click', () =>
  document.querySelector("#randomNum").textContent = Math.floor(Math.random() * 21) + 2);
<button id="btn">generate number</button>
<p id="randomNum"></p>

Here are some helpful hints:

  • utilize hyphens in element IDs
  • keep your code neatly formatted
  • employ document.querySelector() rather than document.getEementById()
  • use element.textContent instead of element.innerHTML

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

Image carousel with interactive buttons

I've taken over management of my company's website, which was initially created by someone else at a cost of $24,000. We recently made some edits to the slideshow feature on the site, adding buttons that allow users to navigate to corresponding p ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

Interactive tabs displaying real-time information

My goal is to create tabbed content based on a tutorial I found online. Following the tutorial step by step works perfectly, but now I want to take it a step further and make the tabs dynamic. The issue arises when some tabs have no content, so I need to g ...

In order to check a checkbox, you need to ensure that the scrolling div has been scrolled to the very

I have a situation where I need to ensure that a user has scrolled to the bottom of a disclaimer before they can acknowledge it by checking a checkbox. Our legal department requires this extra step for compliance reasons. Here is an example of how the mark ...

Is there a way to implement a css/javascript property specifically for a div that is selected in the url?

Take for instance the scenario where I possess the URL example.com/#foo. In this case, CSS styling will be directed to the div with the id foo. If achieving this solely in CSS is not feasible, what methods in JavaScript or jQuery can be used efficiently ...

The Mantine date picker is causing an error stating that objects are not valid as a React child

I'm currently experimenting with utilizing Mantine Date in NextJS. The goal is to have the selected date displayed in the HTML text heading when a user clicks on it. For instance, if a user selects January 1st, 2023, the text should show like this: Da ...

Ways to dynamically update the value of an object property within reactJS state

In the scenario where a component holds state like so: this.state = { enabled: { one: false, two: false, three: false } } What is the proper way to utilize this.setState() in order to set the value of a dynamic property? An attempt such ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

Importing JSON data into JavaScript

For the past few hours, I've been attempting to load a JSON file into JavaScript to feed map coordinates to the Google Maps service. Unfortunately, my script is incomplete and I cannot obtain any results. Here's what I have so far: <script&g ...

When using Jsoup, make sure to nest the <div> tag within an <a>

As per the findings in this response: Referring to HTML 4.01 guidelines, <a> elements are limited to inline elements only. Since a <div> is a block element, it should not be placed within an <a>. However... In HTML5, <a> elements are all ...

Acquiring an alternative data structure in JavaScript or JSON

When clicking on a div with different attributes, I am attempting to retrieve a data object. Here is an example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var locA = { "fro ...

Having trouble with the react event handler for the renderedValue component in Material UI?

I am facing an issue while trying to utilize the onDelete event handler within the chip component using Material UI in the code snippet below. Upon clicking on the chip, it triggers the Select behavior which opens a dropdown menu. Is there a way to modif ...

Enhancing your scheduling capabilities with Kendo UI Web Scheduler - Dynamically managing resources dataSource

I've been attempting to dynamically change the resources dataSource in my Scheduler, but unfortunately, the changes I am making are not reflecting in the Scheduler interface. Here is how I have set up the scheduler: $("#scheduler").kendoScheduler ({ ...

The size of the elements inside a div should be proportional to its parent div

I am struggling with sizing elements within a div. I have set the max-width to 40% and max-height to 25%, and inside is an image that I want to be 80% of its parent div. Here is the code snippet for reference: <div className="inputbox-container&qu ...

Error: Incorrect data input in Django calendar form

I have a DateForm class defined in my form.py file: class DateForm(forms.Form): date = forms.DateTimeField( input_formats=['%m/%d/%Y %H:%M'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control dateti ...

Guide on shifting an element into a different one with the help of jQuery

I'm attempting to relocate an element within another in order to enable a css :hover effect. <ul> <li id="menu-item"> //move into here </li> </ul> <div class="tomove">...</div> 'tomove' is set to dis ...

How can I align a div in a vertical manner if it is displayed as a circle?

This is the creation I have come up with: This is the design I am aiming for: Below is the code I have written: <div id="OR"><span style=" vertical-align: middle;background:blue;">OR</span></div> Here is the corresponding CSS: ...

Unable to display background image on Webpage due to blank page issue while uploading it with HTML and CSS

I've been attempting to build a webpage with an image as the background, but I seem to be facing some issues. Instead of seeing the desired image, all I get is a blank white page. The folder named "images" is located in the same directory as my HTML a ...

Draggable resizing of the Accordion component in React.js using Material-UI

In the visual representation, there are two Accordions—one positioned on the left (30%) and the other on the right (70%). Upon clicking the button, the right accordion disappears, while the one on the left expands to cover the full width (100%). A featu ...