Generating unique modals for each element in php - javascript

I have this project where the user selects an item from a list (fetched from a MySQL database), then outputs buttons named from the item
as such:
My (stripped down) code so far:
<!DOCTYPE html>
<html>
</head>
<body>
<h2>Select User:</h2>
<div>
<form method="POST">
<table border="5">
<thead>
<th></th>
<th>Subject</th>
</thead>
<tbody>
<?php
include('get.php');
$query=mysqli_query($conn,"select * from `subjects`");
while($row=mysqli_fetch_array($query)){
?>
<tr>
<td><input type="checkbox" value="<?php echo $row['subject']; ?>" name="id[]"></td>
<td><?php echo $row['subject']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div>
<h2>Subjects selected:</h2>
<?php
if (isset($_POST['submit'])){
foreach ($_POST['id'] as $id):
$sq=mysqli_query($conn,"select * from `subjects` where subject='$id'");
$srow=mysqli_fetch_array($sq);
?>
<button class="button animate" id="myBtn">
<span>
<?php echo $srow['subject']; ?>
</span>
</button>
<?php
endforeach;
}
?>
</div>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
<script>
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
I was able to make a modal for one button but I want to make a unique modal for each button. How can I do this? Thanks.

Write a function which will build a modal for you. Have this function accept some input, like the content of the modal which you want to show. Then add the modal to the page. This way you can generate an infinite amount of different modals based on the button that you click on.
I've made an example below which demonstrates how this could work. The example works with building a modal, with the same structure of your example, and use the value attribute of the button the set the content of that modal. For simple text this works fine, but for larges chunks of HTML you might consider getting your content from a hidden element and copy the innerHTML value of that element.
// Flag for checking if a modal is already opened.
// This way we can keep track of the opened modal and
// not open a second one before closing the first.
let modalOpen = false;
function createModal(html = '') {
// Create the elements.
const modal = document.createElement('div');
const content = document.createElement('div');
const close = document.createElement('span');
// Add classes to the elements.
modal.classList.add('modal');
content.classList.add('modal-content');
close.classList.add('close', 'js-close-modal');
// Add content to the elements.
content.insertAdjacentHTML('beforeend', html);
close.innerHTML = '×';
// Append children to parents and to the document.
content.appendChild(close);
modal.appendChild(content);
document.body.appendChild(modal);
return modal;
}
// Listen for clicks in the document.
document.addEventListener('click', event => {
// If the create modal button has been clicked, create a modal.
const button = event.target.closest('.js-create-modal');
if (button !== null && modalOpen === false) {
const html = button.value;
createModal(html);
modalOpen = true;
}
// If the close modal has been clicked, remove the modal.
const close = event.target.closest('.js-close-modal');
if (close !== null) {
const modal = close.closest('.modal');
modal.remove();
modalOpen = false;
}
});
*, *::before, *::after {
box-sizing: border-box;
}
.modal {
display: block;
position: fixed;
top: 50%;
left: 50%;
width: 100%;
height: 90%;
max-width: 32em;
max-height: 48em;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.25);
padding: 15px;
transform: translate(-50%, -50%);
background: #ffffff;
border: 1px solid #d0d0d0;
border-radius: 5px;
z-index: 99;
}
.modal-content {
padding: 15px;
}
.close {
position: absolute;
top: 15px;
right: 15px;
cursor: pointer;
}
<button class="js-create-modal" value="This is my first modal.">Modal 1</button>
<button class="js-create-modal" value="All the modals have their own content.">Modal 2</button>
<button class="js-create-modal" value="And are unique in every way.">Modal 3</button>
Another way would be to have a single modal on the page, which you show and hide. Whenever you click a button, you should modify the content of the modal based on the button that you clicked. That way you only have to modify a single piece. But hey, if a modal is hidden, why not just remove it and build a new one when you need it? Your choice.

Related

How do I get the ViewButton to not copy the old note.value

//javascript, this is where I'm having the issue
const form = document.querySelector("#Form");
const note = document.querySelector("#Note");
const table = document.querySelector("#noteTable");
const count = 0;
form.addEventListener("submit", (e) => {
e.preventDefault();
if (note.value !== '') {
const btn = document.createElement("button");
btn.innerHTML = "View Details";
const row = table.insertRow();
const noteRow = row.insertCell();
const viewD = row.insertCell();
noteRow.innerHTML = note.value;
viewD.append(btn);
model.append(note.value);
note.value = "";
btn.addEventListener("click", () => {
model.classList.add("show");
});
const close = document.querySelector("#close");
close.addEventListener("click", () => {
model.classList.remove("show");
});
} else {
alert("Write a note!");
}
});
css button {
color: black;
background-color: green;
}
body {
background-color: rgb(182, 215, 227);
min-height: 100vh;
margin: 0;
}
.model-container {
background-color: rgba(245, 222, 179, 0.38);
position: fixed;
display: flex;
justify-content: center;
align-items: center;
top: 0;
left: 0;
height: 100vh;
width: 100vh;
opacity: 0;
pointer-events: none;
}
.model {
background-color: white;
}
.model-container.show {
pointer-events: auto;
opacity: 1;
}
.open:hover {
cursor: pointer;
color: white;
}
td {
display: block;
}
<h2>NOTE TAKER</h2>
<h6>Add A New Note:</h6>
<form id="Form" action="#">
<label class="ntag" for="note">Note:</label>
<input class="ntag" name="note" id="Note" type="text" placeholder="Write a note">
<button id="Add">Add Note</button>
</form>
<div class="theTable">
<table id="noteTable">
<tr id="Headers" class="headers">
<th></th>
</tr>
</table>
</div>
<div class="model-container" id="model">
<div class="model">
<button class="close" id="close">Close Me</button>
</div>
</div>
I'm not sure why but the notes repeat in the model-container, after you make another note the first one is still there with the second one right after it.
I thought that it could be the placement, so i put it in the btn function, but it duplicated as well; also sorry for how ugly this is, I'm just focused on the JavaScript
If you inspect the source after adding a few notes, you'll notice that it looks like this, assuming I added notes "one", "two" and "three":
It's putting it there because of this line of javascript:
model.append(note.value);
The .append() method doesn't wipe out anything in the <div id="model">, it just adds on to whatever is in there by dumping it after the button or dumping after any existing text.
To avoid erasing the "Close Me" button you'll probably want another div specifically for the text so that instead of using .append() you can just set the .textContent of the element each time. This would be destructive in a way that you wouldn't want to do this on the parent element, because it would wipe out the button. .append() is what is retaining the previous stuff when you click "View Detail."
<div class="model-container" id="model">
<div class="model">
<button class="close" id="close">Close Me</button>
</div>
<div id="txtDetails"><div>
</div>
So instead of using .append() just set the text of <div id="txtDetails"> to what you want it to say by setting the .textContent.
I also added a "data-text" attribute to the button on creation so it would be easier to fish out the text instead of navigating the parent elements and across elements.
Finally, on the click listener event I made it take whatever is stored in the "data-text" attribute and place that into <div id="txtDetails"> so that each "View Details" click would only show what is relevant for that particular note. This method is destructive in that it wipes out and replaces anything in <div id="txtDetails"> with each click but leaves the button in the modal alone.
const form = document.querySelector("#Form");
const note = document.querySelector("#Note");
const table = document.querySelector("#noteTable");
const count = 0;
form.addEventListener("submit", (e) => {
e.preventDefault();
if(note.value !== '')
{
const btn = document.createElement("button");
btn.innerHTML = "View Details";
btn.setAttribute('data-text', note.value);
const row = table.insertRow();
const noteRow = row.insertCell();
const viewD = row.insertCell();
noteRow.innerHTML = note.value;
viewD.append(btn);
note.value = "";
btn.addEventListener("click", () => {
document.getElementById('txtDetails').textContent = btn.getAttribute('data-text');
model.classList.add("show");
});
const close = document.querySelector("#close");
close.addEventListener("click", () => {
model.classList.remove("show");
});
}
else{
alert("Write a note!");
}
});
https://jsfiddle.net/tnqp8L0x/

Hide/Show div and then hide all div

I am trying to make a "meet the staff" section that has hidden bios that display on click. Right now the div displays as it should, but only disappears when the original button is clicked again. I am needing some additional javascript to hide any opened divs when a different (or same) button is clicked. I don't know enough javascript to know what to try in order to make this happen. Thanks in advance!
HTML
<div id="lastname" class="toggle-div" style="display: none;">
<div><p>bio</p>
</div>
</div>
<button class="bio-button" onclick="myBiof()">Click for Bio</button>
Javascript
<script>
function myBiof() {
var y = document.getElementById("lastname");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
</script>
You will need to add some attributes to your HTML to keep track of which item is active, what item a button controls and which ones should be hidden from screen readers. aria-controls aria-expanded and aria-hidden do just that. Once a button is clicked... if it is currently open, just close it (remove active) and toggle the appropriate attributes. If it is not open, close all of them (remove active), open the one you clicked on (add active) and toggle the appropriate attributes. Here is a simple example:
const buttons = document.querySelectorAll("button");
const people = document.querySelectorAll(".person");
const handleClick = (event) => {
const clickedBtn = event.target;
if (clickedBtn.getAttribute("aria-expanded") === "true") {
let personId = clickedBtn.getAttribute("aria-controls");
let person = document.getElementById(personId);
person.classList.remove("active");
person.setAttribute("aria-hidden", "true");
clickedBtn.setAttribute("aria-expanded", "false");
} else if (clickedBtn.getAttribute("aria-expanded") === "false") {
people.forEach(person => {
person.classList.remove("active")
person.setAttribute("aria-hidden", "true");
});
buttons.forEach(button => button.setAttribute("aria-expanded", "false"));
let personId = clickedBtn.getAttribute("aria-controls");
let person = document.getElementById(personId);
person.classList.add("active");
person.setAttribute("aria-hidden", "false");
clickedBtn.setAttribute("aria-expanded", "true");
}
}
buttons.forEach(button => button.addEventListener("click", handleClick));
button {
display: block;
background: transparent;
border: none;
border-bottom: 1px solid #000;
width: 100%;
height: 2rem;
}
.person-container {
width: 400px;
margin: 0 auto;
}
.person {
display: none;
border-left: 1px solid #000;
border-right: 1px solid #000;
border-bottom: 1px solid #000;
padding: 1rem;
}
.person h2 {
margin-top: 0px;
}
.person p {
margin-bottom: 0px;
}
.active {
display: block;
}
<div class="person-container">
<button aria-controls="person-one" aria-expanded="false">Show Person One</button>
<div id="person-one" aria-hidden="true" class="person">
<h2>Name One</h2>
<p>Person One Bio</p>
</div>
<button aria-controls="person-two" aria-expanded="false">Show Person Two</button>
<div id="person-two" aria-hidden="true" class="person">
<h2>Name Two</h2>
<p>Person Two Bio</p>
</div>
<button aria-controls="person-three" aria-expanded="false">Show Person Three</button>
<div id="person-three" aria-hidden="true" class="person">
<h2>Name Three</h2>
<p>Person Three Bio</p>
</div>
</div>
/*
Function to add all the events to the buttons.
Checking if divs are hidden or not with [data-hidden] attribute.
This HMTML attributes can be named however you want but starting
with data-
Note that this code will only work if every button
is placed in the HTML after the bio div
*/
function addEventsAndListenToThem() {
const buttons = document.querySelectorAll('.bio-button')
buttons.forEach(btn => {
btn.onclick = (e) => {
const target = e.target.previousElementSibling
// If element is hided, show it changing
// attribute data-hidden value to false
target.getAttribute('data-hidden') === 'true' ?
target.setAttribute('data-hidden', 'false') :
target.setAttribute('data-hidden', 'true')
}
})
const hide_or_show_all = document.querySelector('.bio-button-all')
// Var to check wether .bio-button-all
// has been pressed or not
var showing = false
hide_or_show_all.onclick = () => {
// Get al divs with data-hidden property
const all_bios = document.querySelectorAll('div[data-hidden]')
showing === false ? (
() => {
// Show all divs
all_bios.forEach(bio => bio.setAttribute('data-hidden', 'false'))
showing = true
}
)() :
(
// Hide all divs
() => {
all_bios.forEach(bio => bio.setAttribute('data-hidden', 'true'))
showing = false
}
)()
}
}
addEventsAndListenToThem()
/*
Display none only to [data-hidden="true"] elements
*/
[data-hidden="true"] {
display: none;
}
.bio-button,
.bio-button-all {
display: block;
margin: 10px 0px;
}
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>First bio</p>
</div>
</div>
<button class="bio-button">Click for first Bio</button>
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>Second bio</p>
</div>
</div>
<button class="bio-button">Click for second Bio</button>
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>Third bio</p>
</div>
</div>
<button class="bio-button">Click for third Bio</button>
<button class="bio-button-all">Show/Hide all</button>

How to show different <div> in one modal?

How can i show (toggle) different divs in one modal? Let me explain:
- when i click on "show me more" i wanna trigger modal (and its working in my case)
- next, i close it (it works)
- i wanna trigger modal again but on different div and offcourse i want this div to be in modal again (now thats where i got stuck at).
Below its snippet of my code...
HTML:
<div id="modal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<div id="wrapper" class="modified">
<!-- Main -->
<section>
<div class="inner">
<h1 class="major">DJ ZA POROKE</h1>
<p align="justify">some text</p>
<p align="justify">some text</p>
</div>
</section>
</div>
</div>
</div>
JS:
var modal = document.querySelector(".modal");
var trigger1 = document.querySelector(".trigger1");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger1.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
And lets say i trigger it like:
<div class="middle">
<div class="text trigger">Show me more..</div>
Thanks for your help.
Regards.
So to get it right:.
user clicks a button /other element ("show me more") and a
modal is shown with content 1
modal is closed
user clicks again a button /other element ("show me more") and a
modal is shown with content 2.
modal is closed
You have 2 options:
call two different modals identical except for the content -> this can be done with a state var in JS
var stateContent = 0;
and check on the button click event in which state we are
The second more elegant shows/hides the relevant div
HTML addapted
<div id="modal" class="modal">
<div class="modal-content">
<span class="close-button">×</span>
<div id="wrapper" class="modified">
<!-- Main -->
<section>
<div id="content_1" class="inner" style="display: block"> <!-- ID added This part is shown -->
<h1 class="major">DJ ZA POROKE</h1>
<p align="justify">some text</p>
<p align="justify">some text</p>
</div>
<div id="content_2" class="inner" style="display: none"> <!-- ID added This part is hidden -->
<h1 class="major">XY ZZ POROKE</h1>
<p align="justify">some OTHER text</p>
<p align="justify">some OTHER text</p>
</div>
</section>
</div>
</div>
</div>
In javascript you change the display style - for simplification I do it on the close button
closeButton.addEventListener("click", function(e){
switchContent();
toggleModal();
});
New function for doing what we want content switching:
function switchContent(){
var content1 = document.getElementById("content_1");
var content2 = document.getElementById("content_2");
// Check in which state we are
if (content1.style.display === 'none') {
content1.style.display = 'block';
content2.style.display = 'none';
}
else {
content1.style.display = 'none';
content2.style.display = 'block';
}
}
I just opened editor at w3 so i can show directly what i want:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<button id="myBtn2">Open Modal2</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..1</p>
</div>
</div>
<!-- The Modal -->
<div id="myModal2" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..2</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById("myModal");
var modal2 = document.getElementById("myModal2");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var btn2 = document.getElementById("myBtn2");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
btn2.onclick = function() {
modal2.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
span.onclick = function() {
modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
if (event.target == modal2) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
So you see something went wrong, because when i click OPENMODAL2 it freezes. But anyhow, i want 8 different divs to show in 1 modal.

Modal pops up after Ajax call completes instead of before or during

I am trying to get a modal popup to show "Please Wait" while an Ajax call is being made. The pop up occurs only after the call completes.
When I click my web link, everything is working, except the modal popup that is supposed to say "Please Wait" flashes for a split second AFTER the delay that the user is supposed to be asked to wait thru. That is, the modal pops up AFTER the Ajax call is completed instead of before.
When the page loads, it calls AjaxInitialUpdate. This works fine.
The issue is when you click the button that calls AjaxChangePassword.
The function is supposed to pull up a modal, then contact the web server, before finally removing the model and calling the AjaxInitialUpdate function to refresh the whole screen.
The issue is that the AjaxChangePassword modal doesn't pop up until the web query completes (by which time, there is no point in telling the user -- Please Wait).
Now, I am totally self-taught here, so I may be calling things by the wrong name or terms. I welcome any ideas to make it run better, but please be detailed, I'm still very novice in Java.
Also, the last time I did any kind of HTML programming was before Style sheets were the way to go, so I'm kind of having to learn them as well (and refresh on all the rest, so please explain any answer in detail).
Lastly, the server side of this is written in Powershell and is single threaded so I am trying to put as much in the HTML file as possible instead of calling secondary files, like style sheets and images.
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
/* Believe these are not needed.
Imported from web site that I copied the code from.
padding: 8px 8px;
outline: none;
border: none;
border-radius: 115px;
box-shadow: 0 3px #999; */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 70%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#IndividualSystem {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border: 1;
}
#IndividualSystem td, #IndividualSystem th {
text-align: left;
padding: 8px;
color: black
border: 1px solid black;
}
#IndividualSystem tr {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #eeeeee;
}
.tab { margin-left: 40px; }
.button {
display: inline-block;
padding: 8px 8px;
font-size: 12px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #4CAF50;
border: none;
border-radius: 15px;
box-shadow: 0 3px #999;
}
.button:hover {background-color: #3e8e41}
.button:active {
background-color: #3e8e41;
box-shadow: 1 5px #666;
transform: translateY(4px);
}
.button2 {
display: inline-block;
padding: 8px 8px;
font-size: 12px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #000080;
border: none;
border-radius: 15px;
box-shadow: 0 3px #999;
}
.button2:hover {background-color: #df330e}
.button2:active {
background-color: #FD2E02;
box-shadow: 1 5px #666;
transform: translateY(4px);
}
#IndividualSystem {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border: 1;
}
</style>
<Title>Cyber Track</title>
</head>
<body>
<table>
<tr>
<td>blah</td>
<td><h1>Systems and Passwords</H1>
<h3>Information within this page is considered confidential.</h3>
</td></tr>
</table>
<hr>
<input type="hidden" id="Leftlink" name="Leftlink" value="0">
<input type="hidden" id="Rightlink" name="Rightlink" value="0">
<input type="hidden" id="serverID" name="serverID" value="server8\admin-server8">
<input type="hidden" id="count" name="count" value="10"> <!--- Number of servers per page on server list //-->
<!-- The Modals #1 -->
<div id="myModal1" class="modal">
<!-- Modal content -->
<div class="modal-content">
<h4><label id="ModalTextLine1">Loading content from server</label></h4>
</div>
</div>
<!-- The Modals #2 -->
<div id="myModal2" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close2">×</span>
How long do you need the password?
<form action='#'>
<select name="days">
<option value='1' >1 day or less</option>
<option value='7'>between 1 and 2 days</option>
<option value='7'>between 2 and 7 days</option>
<option value='30'>between 7 and 30 days</option>
<option value='365' selected>for up to a year.</option>
</select>
<br>
<input type="submit" value="Process Request">
</form>
</div>
</div>
<script>
// Get the modal
var modal2 = document.getElementById('myModal2');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close2")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it (or actually, just hide it)
window.onclick = function(event) {
if (modal2.style.display != "none")
{
if (event.target == modal2) {
modal2.style.display = "none";
}
}
}
</script>
<!-- End Loaded from function -->
<table id="IndividualSystem"> <!-- IndividualSystem - to define needed style sheet //-->
<tr>
<td style="width: 215px;">Server</td>
<td style="width: 259px;"><label ID="DynServerName">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;">User ID</td>
<td style="width: 259px;"><label ID="DynAdminID">Loading</label></td>
</tr>
<tr>
<td colspan="2"><hr></td>
</tr>
<tr>
<td style="width: 215px;">Checked out status:</td>
<td style="width: 259px;"><label ID="DynLastCheckedout">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;" valign='top' >Last checked out by:</td>
<td style="width: 259px;" valign='top' ><label ID="DynLastCheckedBy">Loading...</label>
<button class="button" onclick="javascript:AjaxCheckOutPassword()" id="PassStatus">Loading</button> <!-- AjaxCheckOutPassword -->
</td>
</tr>
<tr>
<td valign='top' style="width: 215px;">Expected Check In Date:</td>
<td valign='top' style="width: 259px;"><label ID="DynExpectedBack">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;">Date of last password change:</td>
<td style="width: 259px;"><label id="DynLastReset">Loading</label> <button class="button2" onclick="AjaxChangePassword()">Force Change Now!</button>
</td>
</tr>
<tr>
<th colspan="2">Notify:<br>
<table border="1" padding = "0" width=100%>
<tr>
<td width=200>On Use:</td><td><label id="DynEmailCheckOut">Loading</label></td>
</tr>
<tr>
<td width=200>On Checkin:</td><td><label id="DynEmailCheckIn">Loading</label></td>
</tr>
</table>
</th>
</tr>
<tr><td colspan="2">
<label ID="DynAccountPurpose"></label>
</td></tr>
</tbody>
</table>
<!-- Page Footer (if any) //-->
<!-- Page links left/up/right //-->
<table>
<tr><td width = 50>
<label id="Show-Left">
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(-1)" text='Prior Server'>
<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAEAAAAAAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAgABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD9+Wwp/wDrVzHxS+Kmk/B3wfda3rdz9lsbPZ5kvlvJ951QfKis3V1HA7074ofE/SPhD4RvNc1m5+x6fZ7PNl8t5Nu50ReFBJyzgcDv6Dj853k8Zf8ABW/4sgY/sv4d6T0X9zPjzIfX9xNzPae/X+6Ob9naPtJ7GXM5Plgfod8H/jHoXxw8FW3iDw7c/btPvt4WTy5I87JHj6SKp+8jfwj8etddvHp+hrm/hb8L9H+EnhO30PQ7f7JZWe7am93xvdnPLsx6sT1P8q6QcDjbjt8prGPdm0rHjv7Yf7JOj/tW/DuTS9Q/0e6jx5M+Hfyv3sTt8qyIDkRAc9O1fH/7GP7T+t/sN+P4/hD8TB5OnQ5+yXX7t/s+Y5rt/kt45C2WmiHMnGeOMgfpEWJb73H0614v+2N+x1oP7WfgiTT9SBt7+HBtrr94/lZkhZvkWRAciEDn8OldCqc0fZzMJU+WXNA9hsb9NQtVlhfdG2drYIzg4PWp8r/drzb9lv4I3fwH+EWn+HNQ1X+2JrPzM3H2YW+7dNLJ90MwGBIB949Pwr0kx8/d/SsIO2jOjRn/2Q==' alt='go to prior server' height='26' width='32'>
</a>
</label>
</td>
<td>
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(0)" text='Next server'>Return to main list</a>
</td>
<td width = "50">
<label id="Show-Right">
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(1)" text='Next server'>
<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAgABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD97dc1U6Zp000cfnPHt+Tdt3ZIHX8a+Z/2Sv8AgpDpfx98c3/hjWNP/wCEf16Dy/Kt/Pe78zMcsp+ZYVQYSMHk/wAXqK+oihPT8DXx7/wUM/4J8r8Wo4/GXg5fsfi7T85XPmfat/2eH/lrMsabYkf+E5z64NEHGM+WezFUTcbw3PsMgtjj6nNO8pfSvjn/AIJv/wDBRD/hoLTj4b8UDyPFFr99s7vtG43Eg4jhWNdsca9+frmvsPa3/PX/AMdrSdKUHZkQqxmtCPULyK1tXef5YVxuPJ7+3PWvzt/a4/a28S/tm/Ek/Cz4V/vrOX/j7u/3S+ZiKK6T5LmOMjBhlHD+57A/ofqenQ6hbPFP80BxuXkdwRyOetef/Aj9lXwh+zpHer4a077AL7y/NP2iaXds34/1kj4/1jdPWsYqLneey/E0nJqP7vcwv2Ov2OdD/ZM+H/8AZunjzr64/wCPy7zIv2jbJMyfI0jhdolI4PPU+3su5fX9KAdwyRgntmn7hWs6spvmkZwpRjsf/9k=' alt='go to prior server' height='26' width='32'>
</a>
</label>
</td>
</tr></table>
<!-- End Page links left/up/right //-->
<!-- Dynamic JAVA Script Section //-->
<script>
// disable our NAV pointers till later where we may re-enable them.
document.getElementById('Show-Right').style.display = 'none';
document.getElementById('Show-Left').style.display = 'none';
//
// This is the specific function that I need help with.
// Why does this modal pop up only after the actual query is done?
//
function AjaxChangePassword(){
document.getElementById('myModal1').style.display = "block";
document.getElementById('myModal2').style.display = "none"; // Make sure its not poped up..
// we need to set item on the modal to explain what we are doing...
document.getElementById("ModalTextLine1").innerHTML="Processing password change request. Please Wait"
var xhr = "";
var xhr = new XMLHttpRequest();
// server will check if values are valid..
var Server = document.getElementById("DynServerName").innerHTML;
var AdminID = document.getElementById("DynAdminID").innerHTML;
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=change&server=' + Server + '/' + AdminID+'&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Comment Response onpassword change.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
console.log("Report password changed.");
AjaxInitialUpdate() // password changed, lets refresh.
};
};
};
xhr.send(null);
document.getElementById('myModal1').style.display = "none";
};
// Navigate left and right..
function AjaxNavigate(link)
{
xx = document.getElementById('Leftlink').value
xx = document.getElementById('Rightlink').value
if (link == 0)
{
// Back to the main page. Get the values that make who we are -- servername and count.
var count = document.getElementById('count').value;
var CurrentSystem = document.getElementById('serverID').value;
var x = '/CyberPass3/?command=homepage&server=' + CurrentSystem + '&count='+ count + '&NoCache=' + ((new Date()).getTime());
location.replace('/CyberPass3/?command=homepage&server=' + CurrentSystem + '&count='+ count + '&NoCache=' + ((new Date()).getTime()));
}
else
{
if (link == 1)
{
document.getElementById('serverID').value = document.getElementById('Rightlink').value
} else {
document.getElementById('serverID').value = document.getElementById('Leftlink').value
}
// we've moved left or right. Lets update.
AjaxInitialUpdate()
}
}
function AjaxCheckOutPassword() {
console.log("Checkout Code not yet written");
};
function AjaxInitialUpdate() {
var xhr = ""
var xhr = new XMLHttpRequest();
var count = document.getElementById('count').value;
var link = document.getElementById('serverID').value
document.getElementById('myModal1').style.display = "block"; // show we are updating everything..
document.getElementById('myModal2').style.display = "none"; // should already be hidden, but lets make sure..
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=refresh&server=' + link + '&count=' + count + '&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Response.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
WebFields = xhr.responseText.split("|");
document.getElementById("DynServerName").innerHTML = WebFields[0];
document.getElementById("DynAdminID").innerHTML = WebFields[1];
document.getElementById("DynLastCheckedout").innerHTML = WebFields[2];
document.getElementById("DynLastCheckedBy").innerHTML = WebFields[3];
document.getElementById("DynExpectedBack").innerHTML = WebFields[4];
document.getElementById("DynLastReset").innerHTML = WebFields[5];
document.getElementById("PassStatus").innerHTML = WebFields[6];
document.getElementById("DynEmailCheckIn").innerHTML = WebFields[7];
document.getElementById("DynEmailCheckOut").innerHTML = WebFields[8];
// if no comment, don't even dispay the table cells.
if (WebFields[9].slice(0,1) == "{" && WebFields[9].slice(-1) == "}" && WebFields[9] != "{}" )
{
var res = WebFields[9].split("{");
var res = res[1].split("}")[0];
document.getElementById("DynAccountPurpose").innerHTML = "<tr><td style='width: 474px;' colspan='2'><p><b>Account Comments:</b></p><p class='tab'>" + res + "</p></td></tr>";
}
else
{
document.getElementById("DynAccountPurpose").innerHTML = "";
console.log("No Comment");
};
// lets populate the nav buttons..
if (WebFields[10] == '\\')
{
// hide go left
document.getElementById('Show-Left').style.display = 'none';
document.getElementById("Leftlink").value = "0/0"
}
else
{
//Enable go left
document.getElementById('Show-Left').style.display = 'block';
document.getElementById('Leftlink').value = WebFields[10];
};
// lets populate the nav buttons..
if (WebFields[11] == "\\")
{
// hide go right
document.getElementById('Show-Right').style.display = 'none';
document.getElementById("Rightlink").value = "0/0";
}
else
{
// Enable go right
document.getElementById('Show-Right').style.display = 'block';
document.getElementById("Rightlink").value = WebFields[11];
};
document.getElementById('myModal1').style.display = "none";
}
if (xhr.status === 403) {
console.log(xhr.response);
document.getElementById("PassStatus").innerHTML = 'Access Denied';
}
if (xhr.status === 404) {
console.log(xhr.response);
document.getElementById("PassStatus").innerHTML = 'Unable to load';
};
}
else
{
document.getElementById("PassStatus").innerHTML = "Failed";
};
};
xhr.send(null);
};
// Now, load the initial value..
window.onload = AjaxInitialUpdate();
</script>
When I call AjaxChangePassword(), I expected the modal to open BEFORE the query.
As it is now, if I stop the server after the page loads, but before this function is started, the modal never pops up, then once I start the server side back up, and I see the query come in and get answers, only then does it pop up, and then only for a split second.
What am I doing wrong in the way I am calling it?
As I reviewed your code and found that in the function AjaxChangePassword firstly you opened modal and then called ajax then closed modal the problem is that basically javascript executes synchronously but if there is ajax call then it executes asynchronously, so according to that your modal opens and then call ajax untill ajax is busy in getting response before that next line will be executed that line is for modal close and this happens in the fraction of ms so you don't see anything, And you said that after ajax call modal is showing because in AjaxChangePassword the call back method is AjaxInitialUpdate and also in this method you opened modal then closed but remember in this method you closed modal in the call back method so it appears for some time and you can see so according to me just remove
document.getElementById('myModal1').style.display = "none";
this line from AjaxChangePassword method below is corrected AjaxChangePassword function
function AjaxChangePassword(){
document.getElementById('myModal1').style.display = "block";
document.getElementById('myModal2').style.display = "none"; // Make sure its not poped up..
// we need to set item on the modal to explain what we are doing...
document.getElementById("ModalTextLine1").innerHTML="Processing password change request. Please Wait"
var xhr = "";
var xhr = new XMLHttpRequest();
// server will check if values are valid..
var Server = document.getElementById("DynServerName").innerHTML;
var AdminID = document.getElementById("DynAdminID").innerHTML;
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=change&server=' + Server + '/' + AdminID+'&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Comment Response onpassword change.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
document.getElementById('myModal1').style.display = "none";
console.log(xhr.response);
console.log("Report password changed.");
AjaxInitialUpdate() // password changed, lets refresh.
};
};
};
xhr.send(null);
};
and check. I may be wrong but check it.

MyWindow=window.open using pop windows and return to parent page

I am using two buttons in my web page (http://localhost:8088/hse/public/explorer) :
and those button will open a new pop window : (http://localhost:8088/hse/public/explorer/1)
onClick="MyWindow=window.open('http://localhost:8088/hse/public/explorer/1','MyWindow',width=300,height=200); return false;">Show Map</button>
This button on clicked it will open a new pop window and inside that pop windows, there will be some HTML links, i want when user click on any of those link , the pop windows close and that link open on the same parent page but different URL (http://localhost:8088/hse/public/explorer/show/1)
Try this.
This wont work when you run the "snippet" ... Create a document and use it there instead.
document.getElementById("button").onclick = evt => {
window.open(window.location.origin + "/hse/public/explorer/1", "MyWindow", "width=300, height=200");
}
<button id="button">Open new window</button>
Update:
Try doing this instead what you described down below. This will do the same, but actually makes sense to use. If you want to create something that is ensured to be userfriendly.
var id_button = document.getElementById("button"),
id_container = document.getElementById("container");
id_button.onclick = evt => {
// show or hide container
if (id_container.classList.contains("hide")) {
id_container.classList.remove("hide");
} else {
id_container.classList.add("hide");
}
}
// add onclick-function for every child of "id_container"
for (var i = 0; i < id_container.childElementCount; i++) {
var child_element = id_container.children[i];
child_element.onclick = evt => {
// check that the element is a "a"-element
if (evt.target.localName == "a") {
window.open(window.location.origin + evt.target.getAttribute("data-link"), "_blank");
}
}
}
.container {
border: 1px solid black;
border-radius: 5px;
text-align: center;
padding: 10px;
}
.hide {
display: none;
}
<button id="button">Show/hide all links</button>
<br><br>
<div id="container" class="container hide">
Link1
<br>
Link2
<br>
Link3
</div>

Categories