Struggling to apply the onclick function to an HTML element

I am working with an array of 10 elements that I need to shuffle and display, which my current code is able to do. However, the issue arises when I try to add functionality to show an alert message if any of the displayed array elements are clicked. The problem I am facing is that when using onclick, it only shows one array element instead of all 10, and also throws an error in the console: Uncaught TypeError: Cannot set property 'onclick' of undefined. Below is the JavaScript code I am currently using:

 <script>
    function shuffleArray(array) {
            for (var i = array.length - 1; i > 0; i--) {
                var j = Math.floor(Math.random() * (i + 1));
                var temp = array[i];
                array[i] = array[j];
                array[j] = temp;
                }
            return array;
        }

    var myArray = ['1','2','3','4','5','6','7','8','9','10'];

    newArray = shuffleArray(myArray);

    for (i=0;i<newArray.length;i++) {
        var p = document.write(newArray[i] + "<br >");
                    p.onclick = showAlert; // this is showing me only 1 array element and also showing error in concole
    }

             function showAlert() {
                      alert("onclick Event detected!")
             }
 </script>

Answer №1

To properly bind events, you should generate a real element rather than attempting with strings:

for (let i = 0; i < newArray.length; i++) {
    const paragraph = document.createElement('p');
    paragraph.innerHTML = newArray[i];
    paragraph.onclick = displayAlert;
    document.body.appendChild(paragraph);
}

http://jsfiddle.net/92fRb/1/

Answer №2

Cannot assign 'onclick' to an undefined property

Here's the issue... when you try to use p, it is not defined.
Why?
Because when you utilize document.write, it does not return a DOM element. In fact, it does not return anything at all (or returns undefined).

The solution is simple:

  1. Utilize document.createElement() to create the element.
  2. Use p.innerHTML to set the content of your new element.
  3. Append your newly created element to the document.

You can update your code as suggested in @Johan's answer.

Answer №3

for (j=0;j<brandNewArray.length;j++){
    var q = document.write("<span class='yes'>"+brandNewArray[j] + "</span><br />");
}

function displayMessage(){
    alert("onclick Event triggered!")
}

for(j=0;j<document.getElementsByClassName("yes").length;j++){
    document.getElementsByClassName("yes")[j].onclick=displayMessage;
}

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

Using jQuery to Verify Matching Objects Based on a Shared Property in Sets

I am in search of a solution using JavaScript or jQuery to ensure that two sets/arrays of objects share the same value for a particular property. In this case, two items share the same guid value across both sets, but some properties differ between them - ...

Issue with PHP $_GET function not functioning properly in conjunction with JQuery Mobile

I am currently developing an application using a combination of JQuery Mobile and PHP. The issue at hand is as follows: I am encountering difficulties when attempting to transfer values between different pages in my JQuery mobile app (for example, from #p ...

Utilizing HTML and jQuery to load a dynamic URL within a div placeholder

I'm experiencing some difficulty with loading a custom URL. Essentially, the user will click on a series of navigation links that will dynamically load the relevant content in a tabbed bootstrap jumbotron. The navigation links vary based on data store ...

Issue with JSONP request in jQuery/AJAX

I am currently attempting to make a request to a different site, which requires authentication through a cookie. Oddly enough, when I try making the call like this : $.getJSON(url + '?', function(data){ alert(data); }); The HTTP headers do ...

Issue encountered in NestJS/TypeORM: Unable to modify the property metadata of #<Repository> as it only has a getter method

When attempting to launch my nestjstutorial app, I encountered the following error message. The backend is connected to a PostgreSQL database. TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:&b ...

I have been utilizing the library phonegap-nfc for scanning NFC tags, but I'm encountering an issue where instead of staying on the current

I have integrated the phonegap-nfc library into my vue project, and it is working fine. However, I am facing an issue where the information from my NFC card is being displayed on a different page instead of within my app. I want to show all the information ...

Why does my POST request result in [object Object] being returned?

I am just starting to learn AngularJS and I am unsure if my POST request is functioning correctly. After making the request, I am receiving an [object Object] response. What does this error indicate? Could it be related to an issue with the form? //Acti ...

Tips for including an element at the start while creating a map()

enum StatusEnum { accepted = "AC", rejected = "RJ", } const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({ value: x, name: x + "_random", })) /** * Console.log(select) * [ ...

I desire a smooth fade-in transition for the background image when the addClass function is

If the background color is set to header-fixed-position, the color will fade in. However, if the background is an image, the image will not fade in. Apologies for my lack of proficiency in English. Please refer to the sample code below. Try removing the c ...

Having trouble getting Uploadify to work as a jQuery Plugin?

The jQuery plugin Uploadify has been implemented on my website, but I am facing issues with the file uploads. The file input is being replaced correctly by Uploadify markup, including the Flash button, however, when selecting multiple files, nothing happen ...

Avoid reactivating focus when dismissing a pop-up menu triggered by hovering over it

I am currently utilizing @material-ui in conjunction with React. I have encountered the following issue: In my setup, there is an input component accompanied by a popup menu that triggers on mouseover. Whenever the menu pops up, the focus shifts away from ...

Steps for implementing target='_blank' on a <Link> tag with more than just an <a> element inside

I'm facing an issue where I need to open a new browser tab and redirect to a specific URL when a button is clicked. The problem arises when using an element other than an anchor tag inside the Next's <Link> element, as it seems to ignore th ...

Viewing full size images in the preview selection zone after selecting a crop circle on reduced large images

Currently, I am integrating the Jcrop jQuery library into my project to enable users to select a round/circular crop area on the images they upload. To see a demo of this functionality, visit their official demo page: However, there seems to be an issue w ...

What is the best way to add a list to a JSON array?

I'm interested in learning how to create a loop using for each and for both methods. I want to access the id "list" in order to append li elements. HTML <div id="list"> <ul> <li>Mainland China</li> ...

How to retrieve input value without the need to click a button or submit the form in PHP

I have an HTML code that includes a hidden input storing a value. I need to retrieve this value and assign it to a PHP variable without requiring any user interaction such as clicking a button. The intended purpose is to use this value for obtaining data f ...

Unable to employ regular array methods

What is the reason behind the inability to use the typical array functions in C# such as: string[] k = {"Hello" , "There"}; k.RemoveAt(index); //Not possible When I rely on code completion, I see suggestions like All<>, Any<>, Cast<> or ...

I'm experiencing an issue with the sub-menu disappearing and preventing me from clicking on any links

Currently, I have set up a navigation bar with a sub-menu that spans the full width of the page. When hovering over the list items, the sub-menu appears as expected. However, when moving the mouse down into the sub-menu, it disappears instantly. The object ...

Issues have arisen with the functionality of IE and jQuery posts

When using jQuery ajax to post to my backend, everything works smoothly in browsers except for Internet Explorer (IE 11). Is there something I am missing specifically for IE? var example = "example/1234"; jQuery.post('#{test_path}', { uri: ...

Tips for maintaining the cleanliness of Node.js, MongoDB, and Socket.io imports

I'm currently utilizing MongoDB, socket.io, and nodeJs. Is there a more efficient way to organize my imports? const express = require("express"); const app = express(); const { createServer } = require("http"); const httpServer = createServer(app); co ...

response cannot be generated outside of the db.query function

router.get('/details/(:id)', (req, res) => { let vehicle_base; db.query("select b.name, count(b.name) AS total_vehicles from base AS b, vehicle AS v where b.id = v.base_id AND b.fleet_id = " + req.params.id , function(err, result){ ...