Use the document.getElementById function in JavaScript to dynamically retrieve elements based on user input in an HTML document. This will

I am currently working towards creating a gallery using pure JavaScript. To start, I am experimenting with a model that involves two buttons - when button #1 is clicked, the string "1.jpg" appears below, and when button #2 is clicked, "2.jpg" is displayed. I aim to achieve this functionality within a single function. Here is what I have implemented so far:

Javascript:

var imageData = new Array(2);
imageData[0] = "1.jpg";
imageData[1] = "2.jpg";

function displayImage() {
    var selection = document.getElementById("selected").value;
    document.getElementById("output").innerText = imageData[selection];
}

HTML:

<button onclick="displayImage()" id="selected" value="0">1</button>
<button onclick="displayImage()" id="selected" value="1">2</button>
<div id="output"></div>

It seems like having two elements with the same ID name ("what") causes issues.
I have attempted to group the buttons inside a div and target them as a whole by using classes or getByName, but it hasn't worked for me. What approach should I take? Is there a better way to handle this? Should I utilize arrays in HTML? How would you tackle this problem?

Thank you!

Answer №1

If you pass in the keyword this as an argument to the function, it will provide the current object that was clicked on within the DOM. This eliminates the need for utilizing IDs:

<button onclick="gallery(this)" value="1">1</button>
<button onclick="gallery(this)" value="2">2</button>

Then, in your JavaScript code, you can use:

function gallery( item ) {
    var selection = item.value;
    ...
}

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

The function $scope.removeNinja cannot be found

As a beginner in Angular, I encountered an issue while working on a project that involved creating a Directory of ninjas with various functionalities implemented using Angular. Here is a snippet of my HTML file: <!DOCTYPE html> <html lang="en" n ...

Prevent tooltip text from appearing when a button is disabled in an angular application

As a beginner in UI development, I have a requirement for my Angular application. I need to enable and disable a button based on certain conditions. The tricky part is that I want to display a tooltip only when the button is enabled. I have managed to chan ...

Updating the Document Object Model

React re-renders only when there is a change in state. However, it may seem like the changes made directly to the real DOM reflect instantly. This might raise questions as to what triggers the re-render when the state remains unchanged. import React from ...

Send a subset of an array to a function

I'm looking for a way to pass a subarray instead of the entire array in C++. For example, I want to pass valid indices starting at array[5] to array[size-1], not from array[0] to array[size-1]. Is there a method to achieve this? ...

Unable to transmit props through components with Vue router

Hey there, I'm currently facing an issue with passing props from my vue router. It seems like nothing is being printed and when I checked in the mounted hook, it's returning undefined. However, strangely enough, when I use console.log(this.$route ...

Error: req.next is not a recognized function in node.js

I am completely stumped by this sudden issue that just appeared out of nowhere, with no changes in the code! TypeError: req.next is not a function The error is occurring at line 120. Here is the corresponding SQL query and the problematic line 120: // Set ...

Converting JavaScript code into PHP syntax

I'm curious about code organization. The original code in this snippet is functioning properly: <?php if (isset($_POST['submit'])){ ... ... $invalidField = 2; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD ...

"Error" - The web service call cannot be processed as the parameter value for 'name' is missing

When using Ajax to call a server-side method, I encountered an error message: {"Message":"Invalid web service call, missing value for parameter: \u0027name\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(O ...

The npm system is encountering difficulties in parsing the package.json file

Having recently started using npm and node, I decided to create a react app with truffle unbox react using npm init react-app. Despite attempting to reinstall npm and clear the cache multiple times, I consistently encounter an error when trying to run sudo ...

Passing array information to a different PHP file

Hey everyone, I need assistance with sending data from 2 PHP files using file_put_contents. I want the data to be stored in the following format: [{"First_Name":"jacob","Last_Name":"caliph"},{"First_Name":"joseph","Last_Name":"jones"},{"First_Name":"Emil ...

How can Angular be used to dynamically show or hide an element based on its height?

Is there a way in Angular to display a "Read More" link once the height of a paragraph reaches 200px? I'm looking for an elegant solution. Here are my elements: <section class="mynotes" ng-if="MyController.mynotes"> <p ng-bind="MyController ...

Convert the date and time of "2018-03-31T05:37:57.000Z" to a

I need help converting the universal time 2018-03-31T05:37:57.000Z to a timestamp in the form of 1520919620673. Can someone please provide guidance on how I can achieve this conversion? ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

"An error occurs when trying to trigger a .click() event within a list element

There is a list that can contain either plain text or a link. If there is a link present, the entire list element should be clickable. When attempting to execute the following code: if ($('.link').length) { $('li[data-contains-link]' ...

Is it possible to merge several blobs into one zip file using JSzip?

When attempting to download multiple images as a single ZIP file, the result is receiving separate zip files instead. The console log shows that the 'urls[]' array contains different arrays. const fileURLs = window.URL.createObjectURL(result);// ...

The jqueryMobile Dialog persistently opens during pageshow, despite having the cookie already set

My jQuery mobile dialog keeps opening every time the page is refreshed, despite having a cookie set to open it only once. I can't figure out why it's loading without any triggers. Any assistance would be greatly appreciated. JAVASCRIPT function ...

Executing commands following a JSON loop in jQuery

I'm experiencing an issue with jQuery. When my page loads, I fetch a JSON file and loop through its items. However, I am unable to attach any event listeners to the input button that is added. For instance, I want to display an alert message... It s ...

What sets Joomla file inclusion apart from the rest?

Can someone please explain the difference between including a JavaScript script file in the following two ways? I created this within a system plugin in Joomla and included the JavaScript file inside the "onAfterInitialise" function. 1) <script type ...

Vue 3's click event handler does not recognize $options.x as a valid function

I'm encountering a perplexing issue. I am currently in the process of creating a Wordpress plugin using Vue, but unfortunately, I am unable to establish functionality for the @click event. <script> export default { name: "App", me ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...