Presenting a Random Term from an Array in Dual Locations

<input type="button" id="btnSearch" value="Search" onclick="myFunction();" />
<div id="message">
    <p></p>
</div>
<br>
<div id="message">
    <p></p>
</div>


<script type="text/javascript">
    function myFunction() {
        var myarray= new Array ("Drama", "Fable", "Fairy Tale", "Fantasy", "Fiction", "Folklore", "Historical Fiction", "Horror", "Humor", "Mystery", "Mythology", "Poetry", "Realistic Fiction", "Science Fiction", "Short Story", "Tall Tale");

        var random1 = myarray[Math.round(Math.random() * (myarray.length - 1))];
        var random2 = myarray[Math.round(Math.random() * (myarray.length - 1))];

        var display = document.getElementById("message").innerHTML = random1 + ", " + random2;
    }
</script>

I have this script set up and I'm aiming to show two randomly selected words from my array next to each other when the button is clicked. Any assistance will be greatly appreciated!

https://jsfiddle.net/edexxmjo/

Answer №1

Perhaps this solution could work

<button type="button" id="myBtn">Click Me</button>
<div id="message1">
</div>
<br>
<div id="message2">
</div>

Here's a bit of JavaScript

document.getElementById("myBtn").addEventListener("click", handleClick);

function handleClick(event) {
    event.preventDefault();
    document.getElementById("message1").innerHTML = generateWord();
    document.getElementById("message2").innerHTML = generateWord();
}

function generateWord(){
    var wordList = new Array("Drama", "Fable", "Fairy Tale", "Fantasy", "Fiction", "Folklore", "Historical Fiction", "Horror", "Humor", "Mystery", "Mythology", "Poetry", "Realistic Fiction", "Science Fiction", "Short Story", "Tall Tale");

    return wordList[Math.round(Math.random() * (wordList.length - 1))];
}

Answer №2

id is special and unique. If you want to display content in multiple places, you can either use the class selector or create another unique id as shown below:

<div id="message">     
</div>
<br>
<div id="message_2">      
</div>

<script type="text/javascript">
    function myFunction() {
    var myarray= new Array ("Drama", "Fable", "Fairy Tale", "Fantasy", "Fiction", "Folklore", "Historical Fiction", "Horror", "Humor", "Mystery", "Mythology", "Poetry", "Realistic Fiction", "Science Fiction", "Short Story", "Tall Tale");

    var random = myarray[Math.round(Math.random() * (myarray.length - 1))]

    document.getElementById("message").innerHTML=random;
    document.getElementById("message_2").innerHTML=random;
    }
</script>

To Get Elements by ID, Tag, Name, Class, CSS Selector

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

Tips for increasing efficiency in Javascript development by leveraging the power of the computer to automate tasks and minimize manual work

When working with JavaScript, what techniques can be used to develop and test efficiently and accurately while focusing on algorithms rather than mechanics? Are there any useful tools that can be utilized in batch or command line mode (outside of an integr ...

"Having trouble with sound in react-native-sound while playing audio on an Android AVD? Discover the solution to fix this

react-native-sound I attempted to manually configure react-native-sound but I am unable to hear any sound. The file was loaded successfully. The audio is playing, but the volume is not audible on Android AVD with react-native-sound. ...

Press the button to access the URL within the current window

Working with Angular, I attempted to develop a function to open a URL in the current window. However, the code below within the controller actually opens a new window: $scope.openUrl = function(url) { $window.open(url); }; ...when using ng-click=&apo ...

A guide to implementing X-Frame-Options in an express.js web application using node.js

My dilemma involves serving static assets within iframes across various desktop and mobile web clients. Specifically, I am seeking guidance on how to whitelist a select group of origins for allowing the setting of X-Frame-Options headers. This will enable ...

Is there a way to transform a callback into promises using async/await, and convert a prototype function into a standard

I need help converting a code callback function to promises. When attempting to convert the prototype to a normal function, I encounter an error that I can't fix on my own. I am eager to utilize the ES7 async-await feature to avoid callbacks. functio ...

The toggle function for the classList ('open') is functioning correctly and can be seen in the inspect element tool, however, the website is not displaying the associated style

How can I make the .nav show styles in .open after clicking #menu-icon? Note: I used Bootstrap to create the nav HTML <!-- logo --> <div class="logo"> <img src="assets/logo.png" alt="logo g's shop& ...

Guide to building a React project with an outdated edition of Create React App

Currently, I'm following an older tutorial to learn React, and as a result, I need to set up a project using Create React App version 1.5.2. I successfully installed <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204352454 ...

The div height adjustment peculiarities in IE7 and IE8 are causing quite a stir

I recently encountered a problem with my HTML/JS code that I thought was simple. The code is designed to expand the size of a div on mouseover and then collapse it back on mouseout. Here's how the code looks: CSS: .sign-in-up { position: absolut ...

Tips for transferring canvas information from JavaScript to Django using Ajax

Currently, I'm developing a Django application that allows users to activate their webcams and capture photos. These images are stored in a canvas, and my goal is to send this image to Django views so that it can be saved on the server. To trigger th ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

Switching to fullscreen mode and eliminating any applied styles

I'm trying to enable fullscreen mode with a button click. I've added some custom styles when the window enters fullscreen, however, the styles remain even after exiting fullscreen using the escape key. The styles only get removed if I press the e ...

Creating a function that uses setInterval to continuously update the input with a specific value

I am looking to use the setInterval function to continuously update the value of #test1. Additionally, I want the value of #test1 to be cleared and reset to 1 second after the user clicks a button. Example output can be found here: http://jsfiddle.net/eK ...

JQuery does not operate on content that is fetched through ajax requests

I've been struggling with this issue for quite some time now and I just can't seem to figure out what I'm doing wrong. (I suspect it's related to the ajax response) I attempted to upload an image to the server using the uploadifive plu ...

Exploring a JavaScript multi-dimensional array

Hello everyone, I need assistance with manipulating this array: [[2,3,0],[0,4,5]] I am looking to rearrange this array as follows: [[2,0], [3,4], [0,5]] Does anyone have any suggestions on how to achieve this? I am using JavaScript for this project. ...

Ensure that an HTML table row remains fixed on the screen at all times

I'm looking to make a specific row in my HTML table always visible on the screen, either at the bottom if scrolled off or top. The row should scroll normally as part of the table when it's visible on the screen. How can I accomplish this using bo ...

What is the best way to address Peer dependency alerts within npm?

Here is a sample package.json that I am using for my application: dependencies : { P1 : “^1.0.0” // with peer dependency of p3 v1 P2 : “^1.0.0” // with peer dependency of p3 v2 } P1 and P2 both have peer dependencies on ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

Managing input/output requests on Amazon EC2 instances

Having mastered node, javascript, and other technologies the hard way, I am finally on the brink of releasing my debut web application. After signing up for Amazon Web Services and setting up a micro instance to take advantage of the first year's free ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

What could be causing my JavaScript code to not function properly in an HTML document?

Hello, I am a beginner in the world of coding and currently delving into web development. Recently, I was following a tutorial on creating a hamburger menu but I seem to be encountering some issues with the JavaScript code. I have double-checked my Visual ...