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

When attempting to execute the 'npm start' command, an error was encountered stating "start" script is

Encountering an issue when running "npm start." Other users have addressed similar problems by adjusting the package.json file, so I made modifications on mine: "scripts": { "start": "node app.js" }, However, t ...

Is there a counterpart to ES6 "Sets" in TypeScript?

I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below: var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ] const un ...

Encountering NaN values in JavaScript arrays

I'm facing an issue with my HTML code that is supposed to make ball(s) bounce around the canvas. However, when I set the arrays storing the coordinates to random positions and test with alert("Co-ordinates " + (cirX[i]) + " x " + (cirY[i]));, it retur ...

Swapping out the video in real-time using an on-demand script

Recently, I encountered an issue with my blog's YouTube video switcher. It seems that the videos won't play once they are changed, and it is related to a light YouTube embed script that I found here: . I believe this script was implemented to imp ...

Load information into a different entity

I need help with adding new values to an existing object. When I receive some form data from noteValue, I also have additional input data in my component under person that I would like to integrate into noteValue before saving it. let noteValue = form.va ...

Positioning an HTML div

Currently, I am diving into the world of HTML and have included a relative div in my code. Although there are two additional divs positioned before it, they do not overlap; unfortunately, the first two still occupy space above the relative one. My desire ...

Searching in jquery not functioning as intended

Greetings! I'm in the process of creating a live search feature similar to what's demonstrated at this link. However, I've encountered a minor issue with this snippet of code: jQuery("#result").on("click",function(e){ var $clicked = $(e.ta ...

What is the best way to centrally align a Card while keeping the text left-aligned?

New to coding and need some guidance. I'm attempting to create a card that is not the full width of the window. I have specified a cardStyle as shown below. cardStyle:{ width: '95vw' align? : 'center?' textAlign? : &a ...

Utilizing CSS naming conventions to bring order to class inheritance

I'm a bit unclear about the rationale behind using this specific CSS structure: h2.class-name It seems like you could simply use .class-name and apply that class to the h2 element: <h2 class="class-name">Title thing</h2> Unless it&apos ...

"Bootstrap4 - Troubleshooting the Issue of Multiple Carousels Not Function

I attempted to incorporate 2 Bootstrap 4 carousels onto a single page, but encountered issues with the functionality. I utilized this code on my page, however, the last element in the carousel does not cycle correctly. There is a delay of 3 transactions be ...

Storage in private Safari mode is not synced between tabs on mobile devices

In the private mode of mobile Safari, I have successfully stored data in the localStorage. However, when I open my web app in two separate tabs, I notice that the data stored in one tab is not accessible in the other tab. This behavior may be present in ot ...

Share your Facebook link with dynamic parameters

When attempting to create a share URL with GET parameters, I am encountering some issues with double encoding. <a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.bing.com%2Fsearch%3Fq%3Dkeyword" /> This results in a faulty URL, while &l ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

Utilizing HTML5 to automatically refresh the page upon a change in geolocation

I have a web application built with AngularJS. One of the functionalities is activated only when the user is in close proximity to specific locations. To make this work, I can constantly refresh the page every 5 seconds and carry out calculations to dete ...

Challenges with navbar and CSS alignment in Internet Explorer

Looking for some assistance with a HTML/CSS issue... I've created a new menu using the following CSS and code, but I'm encountering a problem with extra space between lines of text within the menu (specifically with the 'big' and &apos ...

Is there a way to switch the language on the date-picker tool?

My date-picker has a unique set up: <input type="text" ng-readonly="true" class="form-control" datepicker-popup="yyyy-MM-dd" ng-model="filter.FInicial" is-open="filter.controlFInicialAbierto" min-date="minDateIni" max-date="maxDat ...

What could be the reason for the presence of three pixels of white space below this particular table

My table is supposed to have a fixed height of 146px, but there seems to be an extra row of three pixels at the bottom. I've tried various methods to remove any unwanted spacing or padding, but nothing has worked so far. The only solution I found was ...

After generating the token, where is the appropriate place to define the authorization header?

I am currently working on implementing a security system based on tokens. The challenge I am facing is determining the appropriate location to set the authorization header after generating it, in order to validate it across all of my different routes. Belo ...

What could be causing WidgEditor, the JavaScript text editor, to fail to submit any values?

After clicking submit and attempting to retrieve text from the textarea, I am encountering a problem where the text appears blank. The reason for this issue eludes me. function textSubmit() { var text = $("#noise").val(); console.log(text); consol ...

The getter method in the Vuex store object seems to be returning varying values when accessing nested properties

Currently, my Vuex store is being used to store a user object. This code snippet is a getter function for the user object: getters: { user: (state) => state, isAuthenticated: state => { console.log("user object", state); ...