Modal Pop-ups Failing to Open on Subsequent Attempts

My table consists of buttons on the right-hand side for a menu. The first button in the menu is supposed to open a modal box upon clicking. However, the first buttons in the subsequent rows do not function as expected and fail to open the modal. Refer to this JSfiddle for a visual representation: https://jsfiddle.net/dsflyerds/6h1qeb2v/2/ HTML

<p>Length DestinationTrain LengthTrain WeightStatusCapicityRemarks </p>
<table border="1" width="100%">
<tbody>
<tr>
... (Table content continues)

JavaScript

//MODAL BAN
var modalt = document.getElementById("trackModal");

// Get the button that opens the modal
var btnt = document.getElementById("trackBtn");

// Get the <span> element that closes the modal
var spantrack = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btnt.onclick = function() {
  modalt.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
spantrack.onclick = function() {
  modalt.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modalt) {
    modalt.style.display = "none";
  }
}

CSS

.modal {
... (CSS styles continue)

Answer â„–1

Repeated unique IDs in your code can cause issues with getElementById, as it only selects the first instance found in the document. To handle multiple elements, use classes and utilize querySelectorAll('.classname').

Replace ID attributes with class attributes in your HTML:

<div class="yardDropdown"><button class="yardDropbtn">Menu<i class="bx bx-menu"></i></button>
  <div class="yard-dropdown-content">
    <button class="trackBtn yardDropBtnCt">Edit Track</button><!--change trackBtn here to class-->
    <button class="yardDropBtnCt">Clear Track</button>
    <button class="yardDropBtnCt">Link3</button>
    <button class="yardDropBtnCt">Link4</button></div>
</div>

Select the nodelist using

document.querySelectorAll(".trackBtn")
:

var btnt = document.querySelectorAll(".trackBtn");

Loop through the nodelist using a forEach loop to find the event handler:

btnt.forEach(btn => {
  btn.onclick = function() {
    modalt.style.display = "block";
  }
})

This will open the modal referenced by the variable modalt. You can set up a dataset attribute to track elements for unique data from PHP.

For example, within the onclick event function:

track = e.target.closest('tr').querySelector('.track');

Set the modal's information using the modal ID and classes from HTML:

For Example on the track:

modalt.querySelector('.pg-Heading').textContent = `Edit ${track.textContent}`;

To display input data in the modal, use .value:

modalt.querySelector('.destination').value = destination.textContent;
.

Ensure proper classes are added to your HTML elements. A static version of your JSFiddle demonstrates handling button clicks and setting unique data within the modal.

Incorporate PHP to dynamically generate tables and modals based on nested arrays. Use JS to populate modal data from table row buttons clicked via e.target. See the provided PHP script below for reference.

Your JavaScript code would look like this:

//MODAL BAN
var modalt = document.getElementById("trackModal");

// Get the button that opens the modal
var btnt = document.querySelectorAll(".trackBtn");

// Get the <span> element that closes the modal
var spantrack = document.getElementsByClassName("close")[0];

let track, destination, length, weight, status, remarks = '';

// When the user clicks on the button, open the modal
btnt.forEach(btn => {
  btn.onclick = function(e) {
    track = e.target.closest('tr').querySelector('.track');
    destination = e.target.closest('tr').querySelector('.destination');
    length = e.target.closest('tr').querySelector('.length');
    weight = e.target.closest('tr').querySelector('.weight');
    status = e.target.closest('tr').querySelector('.status');
    remarks = e.target.closest('tr').querySelector('.remarks');
    modalt.querySelector('.pg-Heading').textContent = `Edit ${track.textContent}`;
    modalt.querySelector('.destination').value = destination.textContent;
    modalt.querySelector('.length').value = length.textContent;
    modalt.querySelector('.weight').value = weight.textContent;
    let statusVal = 2;
    if(status.textContent === "Ready"){
      statusVal = 1
    }else if(status.textContent === "Hump"){    
      statusVal = 3
    }
    modalt.querySelector('.status').value = statusVal;
    modalt.querySelector('.remarks').value = remarks.textContent;
    modalt.style.display = "block";
  }
})

// When the user clicks on <span> (x), close the modal
spantrack.onclick = function() {
  modalt.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modalt) {
    modalt.style.display = "none";
  }
}

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 issue with the jQuery click event arises when utilizing the "Module Pattern"

Exploring the Module Pattern as described by Chris Coyyer here, I, an intermediate front-end JS developer, have encountered a problem. Specifically, when attempting to utilize a jQuery selector stored in the settings object, I am unable to trigger a click ...

What are some ways to modify the appearance of the post title table using CSS?

In this snippet of HTML code- <table style='min-width:60%;height:25px;'> <tr> <td><b><data:post.title></b></td> <td id='date-and-author' style='position: relative;bo ...

Having trouble with using findByIdAndUpdate and push in MongoDB?

As someone who is new to Mongodb, I have been using the findByIdAndUpdate function to update a document in my project. However, I noticed that it returns the old document instead of the updated one. Below is the code snippet of my function: exports.crea ...

Looking for assistance with CSS selectors for the following structure

I am currently working on locating the anchor element "a" that is nested inside a table with the class name table.ic-table-creditReportProduct table tr. I have attempted to find it, but my attempts have been unsuccessful so far. Any suggestions on where th ...

Creating a multi-dimensional array in JavaScript with two different sizes

I'm struggling to find the best way to create a multi-dimensional array with varying sizes dynamically. Our user interface requires a pattern where there are rows of 4 items followed by rows of 3 items. This pattern should continue until all contents ...

Ways to adjust the div height to match the span height

.headerDesc { width: 100% + 1px; height: 70px; background-color: #4d2765; margin: 0 -8px; } .headerDesc span { padding: 5px; position: absolute; color: white; font-family: 'Arial', sans-serif; text-al ...

Create a precise layout for a footer design

I recently revamped a footer using a new UI framework in an attempt to improve it. Despite my efforts to align it properly, I encountered issues with overlapping on the right side. I experimented with using <div> and applying styles to create a diffe ...

Creating a two-dimensional canvas within a div element using the console

I have some code that currently generates an image in the console when I hit F12. However, I would like to display this image inside a more user-friendly area such as a div on the webpage. I attempted to create a <div class = "mylog"> to place the i ...

Troubleshooting URL Problems with Node.js Search and Pagination

My results page has pagination set up and the routes are structured like this: app.get("/results",function(req,res){ query= select * from courses where // this part adds search parameters from req.query to the sql query// Object.keys(req.query.search).for ...

Tips for enhancing contrast in MUI dark theme modals

Currently, I am implementing MUI dark mode for my Next.js application. While the MUI modal functions perfectly in light mode, I am struggling with visibility issues when using it in dark mode. The contrast is not strong enough, making it difficult to disti ...

Exploring Amcharts using detailed JSON data

[{"SUM_PTS":{"datatype":"INTEGER","length":"8","value":"29903727","obfuscated":"false"},"SUM_TOTAL":{"datatype":"INTEGER","length":"10","value":"1644704985","obfuscated":"false"},"MID":{"datatype":"ALPHANUMERIC","length":"27","value":"Vendor 1","obfuscated ...

Transform audio file into a base64 encoding

I am currently developing a Phonegap application for a friend that will allow users to record audio on their phone, save it to the browser's local storage, and then upload it at a later time. As far as I know, local storage does not support storing b ...

Create a dynamic dropbox using JavaScript/JQuery in an HTML page

I am currently working on implementing 3 different drop down boxes that are triggered by 4 different buttons. These drop down boxes should appear within the #apple div. When Button B1 is clicked, the drop down options include Apple, Mango, and Papaya. Whe ...

Creating a CSS background that adjusts to fit any screen resolution

Hey there, I'm a beginner to all of this. I want my background image to adjust to fit any web browser resolution, regardless of the size. So far, I've come across this nifty little trick: html { background: url(images/bg.jpg) no-repeat center ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

Can someone tell me where I can locate the CSS file once I've finished using Scene Builder?

Currently, I am working on my database project using Scene Builder. I have applied some CSS styling and would like to locate the CSS file in order to attach it to my IntelliJ project for further code editing. Can anyone guide me on where to find the CSS ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

The console is reporting an error stating it cannot read the charCodeAt property

<script> var str=prompt('please enter a string'); var a= str.split(''); for (j=0; j<str.length; j++){ for(i=j; i<str.length; i++) { if(a[i].charCodeAt(0) > a[i+1].charCodeAt(0)) { var b= a[i]; a[i]=a[i+ ...

Enhance Your Website with Interactive Tooltips Using Twitter Bootstrap

In Twitter bootstrap, the default trigger for tooltips is hover. If I want to make the tooltip display on focus instead, I can add data-trigger="focus". But how do I make it so the tooltip displays both on hover and on focus? ...

CSS technique to display background on hover

My website has a bootstrap 'More' dropdown feature on the left navigation bar. However, there is an unwanted background hover effect that I can't seem to remove. Despite removing all background hovers from my CSS, the issue persists. Can any ...