Displaying random text through innerHTML is not possible

After hours of working on this JS code, I finally created a function that should select a random message from the list and display it upon clicking a button. However, instead of displaying a different message each time, it keeps showing the same one (test4). I'm stuck and can't seem to figure out how to fix this issue. The console log shows the correct HTML output, so I'm not sure what's causing the problem.

var r_text = new Array();
var r_pm = new Array();

let pm1 = `<p id="pname"></p>
            <h3 id="pm">test1</h3>`

let pm2 = `<p id="pname"></p> <h3 id="pm">test2</h3>`;

let pm3 = `<p id="pname"></p> <h3 id="pm">test3</h3>`;

let pm4 = `<p id="pname"></p> <h3 id="pm">test4</h3>`;

let pm5 = `<p id="pname"></p> <h3 id="pm">test5</h3>`;

function nextPM() {
  getPM();
  getPname();
}

function getPM() {

  r_pm[0] = pm1;

  r_pm[1] = pm2;

  r_pm[2] = pm4;


  i = Math.floor(3 * Math.random())

  let pm = r_pm[i]
  console.log(pm)

  if (pm = pm1) {
    pm1text();
  }
  if (pm = pm2) {
    pm2text();
  }
  if (pm = pm3) {
    pm3text();
  }
  if (pm = pm4) {
    pm3text();
  }
}

function pm1text() {
  document.getElementById("pmdiv").innerHTML = `${pm1}`

  if (pmanswer = fix) {
    goodanswer();
  }
  if (pmanswer = agyogyit) {
    badanswer();
    let hibapont = +1;
  }
}

function pm2text() {
  document.getElementById("pmdiv").innerHTML = `${pm2}`

  if (pmanswer = agyogyit) {
    goodanswer();
  }
  if (pmanswer = fix) {
    badanswer();
    let hibapont = +1;
  }
}

function pm3text() {
  document.getElementById("pmdiv").innerHTML = `${pm3}`

  if (pmanswer = agyogyit) {
    goodanswer();
  }
  if (pmanswer = fix) {
    badanswer();
    let hibapont = +1;
  }
}

function pm4text() {
  document.getElementById("pmdiv").innerHTML = `${pm4}`

  if (pmanswer = agyogyit) {
    goodanswer();
  }
  if (pmanswer = fix) {
    badanswer();
    let hibapont = +1;
  }
}
<div id="pmdiv"></div>
<article>
  <button class="button" id="next" onclick="nextPM();">Next</button>
</article>

Answer №1

The issue lies in your if statement where you are not comparing values but rather assigning them. This results in the last if condition always taking precedence over the previous ones. Make sure to use == for comparison instead of =

var r_text = new Array();
var r_pm = new Array();

let pm1 = `<p id="pname"></p>
        <h3 id="pm">test1</h3>`

let pm2 = `<p id="pname"></p> <h3 id="pm">test2</h3>`;

let pm3 = `<p id="pname"></p> <h3 id="pm">test3</h3>`;

let pm4 = `<p id="pname"></p> <h3 id="pm">test4</h3>`;

let pm5 = `<p id="pname"></p> <h3 id="pm">test5</h3>`;

function nextPM() {
  getPM();
}

function getPM() {

  r_pm[0] = pm1;

  r_pm[1] = pm2;

  r_pm[2] = pm4;


  i = Math.floor(3 * Math.random())

  let pm = r_pm[i]

  if (pm == pm1) {
    pm1text();
  }
  if (pm == pm2) {
    pm2text();
  }
  if (pm == pm3) {
    pm3text();
  }
  if (pm == pm4) {
    pm3text();
  }
}

function pm1text() {
  document.getElementById("pmdiv").innerHTML = `${pm1}`
}

function pm2text() {
  document.getElementById("pmdiv").innerHTML = `${pm2}`
}

function pm3text() {
  document.getElementById("pmdiv").innerHTML = `${pm3}`
}

function pm4text() {
  document.getElementById("pmdiv").innerHTML = `${pm4}`
}
<div id="pmdiv">

</div>
<article><button class="button" id="next" onclick="nextPM();">Next</button></article>

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

Troubleshooting issues with integrating CDN in a NextJs 13 project

Struggling to add a CDN like Remix Icon to my NextJs13 project. Initially tried adding it by importing the 'head' tag and inserting values into the Head component, but that method is no longer working. There seems to be a new way of doing it now, ...

JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script> function DisplayTag(){ var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML; var counter1=0; function executeScript(q1,counter1){ q1= document.getElementById( 'ctl00_Co ...

The else statement is executed when an asynchronous call is made within an if statement

When an asynchronous call is made inside the if block, it raises the question of how the else statement block can be executed if doSubmit returns true. This often leads to reaching the line after the ERROR_2 comment: $scope.save = function() { if (doS ...

Ways to trigger a re-render in useEffect once the data has been updated

My goal is to utilize the useEffect hook to fetch and display the rooms data, and update the rendering when a new room is added to the list. Here is the code snippet that achieves this using useEffect with an empty dependency: const [rooms, setRooms] = use ...

Having difficulty kicking off a fresh React project on Windows

I've encountered an issue while setting up my React application on Windows OS. After running npm start, the application fails to load on localhost:3000, showing the error message Cannot GET /. Below is the project structure: - webpack.config.js - p ...

Is there a way to eliminate the blue border from a Material React Modal?

I am currently using the React Material Modal and noticed that in the demo examples, there is a blue border when the modal is opened. Is there a way to remove this blue border? I have tried setting the disableAutoFocus property to "true" in the Modal Api ...

What is the best way to showcase data from input fields within a bootstrap modal dialog?

After the user has entered their details and clicks submit, I would like to present the information in a Bootstrap modal with a confirmation button below. This serves as a preview of the data before it is saved to the database. Here's what I have so ...

Debounce on React Component

Attempting to add a delay to a react component with an input field that updates when changed Below is the method used for onChange: handleOrderQtyKeyPress (e) { var regex = /[^0-9]/ if (e.key.match(regex)) { e.preventDefault(); } ...

Searching for a RegEx expression or jQuery selector that will exclude "external" links in the href attribute

I am using a custom jQuery plugin to enable Ajax loading of page content when certain links are clicked. Implementing this is straightforward with a delegated event like $(document).on('click','a', function(){});. However, I want this ...

Issues with retrieving the subsequent anchor element using Jquery Slider

(Apologies for the lengthy post. I like to provide detailed explanations.) Just starting out with Jquery, trying my hand at creating a custom image slider from scratch. Got the slider working with fade effects using this code: Javascript: $(document).re ...

The Issue of a Table Without Choices

Seeking clarification on an issue concerning tables. Can anyone help with this? Issue1: I have created a Single Page Application (SPA) with a table in plunker1:http://plnkr.co/edit/LJ81NedMa88Q7EhFrLmw?p=preview (Navigate to Tab2, select a date and submit ...

AngularJS validation loses synchronization when eliminating a form element

I have a form that includes multiple input fields, allowing users to remove them as needed. var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.numbers = [1,2,3]; $scope.deleteField = ...

Is it possible to utilize multiple databases with NestJS and TypeORM?

I've been struggling for the past two days trying to figure this out, but it seems like I'm just not grasping the concept here. My objective was to create a NestJS application (with TypeORM integrated) that could serve as a RestAPI for 2 or 3 of ...

Vue.js implementation of FontAwesome eye icon for toggling password visibility

I am utilizing the font awesome eye icon to toggle the visibility of a password field for user login. Although the icon displays correctly, I am encountering an issue where the entered characters are not being shown. Can anyone provide assistance with this ...

How can I retrieve the text input from a physical barcode scanner in a React Native screen?

Currently, I am developing a mobile application with React Native version 0.68.2. I am seeking a solution to detect barcode scanning events from a physical scanner hardware that is integrated into the mobile device as a handheld scanner. The key requirem ...

What is the best way to incorporate the :after pseudo-element in JavaScript code

HTML: This is my current code snippet <div class="one"> Apple </div> I am looking to dynamically add the word "juice" using JavaScript with the .style property. Is there an equivalent of :: after in CSS, where I can set the content in JavaS ...

Customize your cube with unique ThreeJs text on every face!

I am currently experimenting with Three.js to create a rotating cube with unique text on each face. I have managed to use DynamicTexture to assign text to the faces of the cube, but it is displaying the same text on all sides. Is there a way to display dif ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Creating a great user experience with Knockout JS and Bootstrap Modal

I created a straightforward webpage with a button that triggers the opening of a modal. You can view all my code in this JSFiddle: JS Fiddle Also provided below: $('#displayDetails').click(() => { let obj = { Overview: ' ...

What are the steps to programmatically click a JavaScript button with Selenium and Python?

Imagine there is a button on a webpage that looks like this: <input type="submit" name="next_btn" value="Next" onclick="gonext();" id="btnNext"> When manually clicked, it takes approximately 3-6 seconds for the page to reload and show new content. ...