I'm a beginner in web development and I have a form where you enter your name and surname . Then by clicking submit , a modal box has to pop up in the screen saying that your purchase is complete and by clicking an ok button it has you move to another html page . In my form I have a function that when you submit the form it checks if the name and surname are strings . If they are you have to open the modal box using a function , else return false and enter again . In my page the modal box pops up for a single second and then the page justs reloads . Basically I'm trying to call a function that pops up a modal box after name and surname are validated .
I would appreciate your help with guiding me to solve this task.
Thank you in advance .
My code :
function validateStrings(){
var x = document.getElementById("first");
var y = document.getElementById("last");
if(!(/\d/.test(x.value)) && !(/\d/.test(y.value))){
}
else{
alert('no submit');
return false;
}
popbox(); //after checking if inputs are strings pop up the box
}
function popbox(){
var btn = document.getElementById("submit");
var modal = document.getElementById("mymodal");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick=function(){
modal.style.display="none";
}
//when user clicks on window outside of box close the modal
window.onclick=function(){
if (event.target == modal) {
modal.style.display = "none";
}
}
}
#ondel{
position:relative;
margin:10px auto 0px;
width:500px;
height:250px;
box-sizing:border-box;
background:rgb(0,0,0,0.5);
padding:40px;
border-radius:50px;
}
.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 {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
footer{
font-size:10px;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<div class = "on-delivery-container" id = "ondel">
<form class = "pay">
<label for "First-name"> First Name </label>
<input type = "text" name = "fname" id="first" required>
<label for "Last-name"> Last Name </label>
<input type = "text" name = "sname" id="last" required>
<button type = "button" class = "cancelbtn" onclick = "returntostep2()">Go back</button>
<button type = "submit" class = "submitbtn" onclick= "return validateStrings()">Submit</button> //valideStrings() checks my input
</form>
//my modal box
<div class = "modal" id = "mymodal">
<div class = "modal-content" id = "mymodalcontent">
<span class="close">×</span>
<p> Your purchase is complete ! </p>
<button class = "submitbtn" type = "button" onclick = "window.location.href='Start_page.html';"> OK </button>
</div>
<footer> © BookHouse All Rights Reserved. </footer>
</div>
</div>
Pass the click event to your validateStrings() and use e.preventDefault() to stop the submit button from refreshing the page. Alternatively name the button something other then submit and manually submit your form when you're are ready inside the pop up or validateStrings function
Related
I have a button that tiggers a popin. I appended it to a div and then preppended that div to all divs with the same class.
My problem is that only the last button prepended triggers the popin. The other buttons dont seem to work.
Can anyone help me?
JSFiddle Here
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// 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";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.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";
}
}
$(window).on('load', function() {
function topBannerCaps() {
if ($('#container').css('display') == 'block') {
$('#myBtn').appendTo('#container');
}
$('#container').prependTo('.test-div');
}
requestAnimationFrame(topBannerCaps);
});
Couple of problem in your code.
Id must be unique so use class on button instead of id when append.
Don't mismatch JavaScript and jQuery.
Avoid inline class if possible.
Working Fiddle:
// Get the modal
var modal = $("#myModal");
// Get the button that opens the modal
var btn = $(".myBtn");
// Get the <span> element that closes the modal
var span = $(".close");
// When the user clicks the button, open the modal
btn.on("click", () => {
$(modal).css("display", "block")
});
// When the user clicks on <span> (x), close the modal
span.on("click", () => {
$(modal).css("display", "none")
});
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
$(modal).css("display", "none")
}
}
$(window).on('load', function() {
function topBannerCaps() {
if ($('#container').css('display') == 'block') {
btn.appendTo('#container');
}
$('#container').prependTo('.test-div');
}
requestAnimationFrame(topBannerCaps);
});
.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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Trigger/Open The Modal -->
<button class="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<div id="container" style="display: block"></div>
<div class="example">
<div class="test-div">Example DIV</div>
<div class="test-div">Example DIV</div>
<div class="test-div">Example DIV</div>
<div class="test-div">Example DIV</div>
<div class="test-div">Example DIV</div>
<div class="test-div">Example DIV</div>
</div>
I have a box modal that I created in my view using HTML that is called when the user presses a button called delete if they wanted to delete a request. From here the user sees two buttons, one to confirm the deletion and one the cancel the deletion. However when I click the delete button the box modal pops up but the buttons confirm and cancel don't delete. I am using MVC .NET core Framework for this project and I want the user to be able to delete requests but to be prompted if they are certain that they want to delete them.
#model PsSecurityRequest
<!-- The Modal -->
<button id="mybtn">Delete</button>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<h3>Are you sure you want to permanetly delete this request?</h3>
<span class="close">×</span>
<input type="submit" class="btn btn-primary" value="Confirm" asp-controller="AdminPage" asp-action="Delete" asp-route-id="#Model.RequestId" />
<input type="submit" class="btn btn-primary" value="Cancel" asp-controller="AdminPage" asp-action="Index" />
</div>
</div>
The view that I am using for the box modal is shown here.
function AdminPage() {
//var Status = document.getElementById("ddlState");
//var Confirm = document.getElementsByClassName("Confirm");
//var Cancel = document.getElementsByClassName("Cancel");
//var _Confirm = "Confirm"
//Confirm.classList.add("hide");
//Cancel.classList.add("hide");
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("mybtn");
// 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";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.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";
}
}
}
This is the javascript file that I am using in this project.
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
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/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
Here is the .cs file I am using as well for the box modal.
public IActionResult Delete(int Id)
{
// var id;
//_psSecurityRequestRepository = PsSecurityRequest.GetRequest();
// PsSecurityRequest deleteRequest = _psSecurityRequestRepository.GetRequestById(Request);
PsSecurityRequest securityRequest = _psSecurityRequestRepository.GetRequestById(Id);
//PsSecurityRequest repo = new PsSecurityRequest();
// var _data = repo.Requests();
_psSecurityRequestRepository.DeleteRequests(securityRequest);
return View(securityRequest);
}
This is the action method that is called when the user will confirm to delete a request. Finally here is the repository that has the methods that are seen in the action method within the controller.
public PsSecurityRequest GetRequestById(object id)
{
throw new NotImplementedException();
}
//[HttpPost, ActionName ("Delete") ]
public void UpdateShortEmplId(PsSecurityRequest psSecurityRequest)
{
_appDbContext.Update(psSecurityRequest);
_appDbContext.SaveChanges();
}
public void FixEmplId()
{
foreach(PsSecurityRequest psSecurityRequest in psSecurityRequests)
{
if (psSecurityRequest.SecurityForEmplid.Length < 7)
{
psSecurityRequest.SecurityForEmplid = "0" + psSecurityRequest.SecurityForEmplid;
_appDbContext.Update(psSecurityRequest);
}
}
_appDbContext.SaveChanges();
}
public void DeleteRequests(PsSecurityRequest Request)
{
_appDbContext.Remove(Request);
throw new NotImplementedException();
}
I'm making a note taker app that gives you the option to view said note in a modal whenever the button is clicked. There are two ways the close it by clicking the "X" button or by clicking outside of the modal.
When I proceed with one of these options, the modal will close successfully, but if I open it a second time neither the "X" button or clicking outside seem to work. How could I fix this problem?
class Input {
constructor(note) {
this.note = note;
}
}
class UI {
addNote(input) {
// Get table body below form
const content = document.querySelector(".content");
// Create tr element
const row = document.createElement("tr");
// Insert new HTML into div
row.innerHTML = `
<td>
${input.note}
<br><br>
<button class="modalBtn">View Note</button>
</td>
`;
content.appendChild(row);
// Event listener to make modal
document.querySelector(".modalBtn").addEventListener("click", function(e) {
// Get container div
const container = document.querySelector(".container");
// Create div
const div = document.createElement("div");
// Assign class to it
div.className = "modal";
// Insert HTML into div
div.innerHTML = `
<div class="modal-content">
<span class="closeBtn">×</span>
<div>
<p>${input.note}</p>
</div>
</div>
`;
// Append the new div to the container div
container.appendChild(div);
// Get modal
const modal = document.querySelector(".modal");
// Event listener to close modal when "x" is clicked
document.querySelector(".closeBtn").addEventListener("click", function() {
modal.style.display = "none";
});
// Event listener to close when the window outside the modal is clicked
window.addEventListener("click", function(e) {
if (e.target === modal) {
modal.style.display = "none";
}
});
});
}
// Clear input field
clearInput() {
note.value = "";
}
}
// Event listener for addNote
document.getElementById("note-form").addEventListener("submit", function(e) {
// Get form value
const note = document.getElementById("note").value;
// Instantiate note
const input = new Input(note);
// Instantiate UI
const ui = new UI();
// Validate form (make sure input is filled)
if (note === "") {
// Error alert
alert("Please fill in text field!");
}
else {
// Add note
ui.addNote(input);
// Clear input field
ui.clearInput();
}
e.preventDefault();
});
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 17px;
line-height: 1.6;
}
.button {
background: coral;
padding: 1em 2em;
color: #fff;
border: 0;
}
.button:hover {
background: #333;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #f4f4f4;
margin: 20% auto;
padding: 20px;
width: 70%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-direction: 1s;
}
.closeBtn {
color: #ccc;
float: right;
font-size: 30px;
}
.closeBtn:hover,
.closeBtnBtn:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" integrity="sha512-5fsy+3xG8N/1PV5MIJz9ZsWpkltijBI48gBzQ/Z2eVATePGHOkMIn+xTDHIfTZFVb9GMpflF2wOWItqxAP2oLQ==" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css">
<title>Note Taker</title>
</head>
<body>
<div class="container">
<h1>Note Taker</h1>
<h5>Add A New Note:</h5>
<form id="note-form">
<div>
<label>Note:</label>
<textarea name="Note" id="note" class="u-full-width"> </textarea>
</div>
<div>
<button type="submit" class="button-primary">Add Note</button>
</div>
</form>
<table>
<tbody class="content"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
That happens because when you apply
modal.style.display = "none";
to the modal, you aren't destroying it, you're only hiding it. Additionally, every time you create a modal, and use
const modal = document.querySelector(".modal");
you aren't receiving the new modal you appended to the container, you're receiving the one that it's hidden. That's why the click event doesn't work, because it's being added to the hidden modal. To fix that change,
this:
modal.style.display = "none";
to this:
container.removeChild(modal);
in both EventListeners
I created a pop up box that appears when a user clicks a button. Currently I am able to get the box to appear but when the user closes it and re-opens it the code is ran through again and another box is stacked on top of the old one.
What I want to do is make it so no matter how many times the user clicks the box it only shows one box... my thoughts was maybe checking if it was empty similar to How do I check if an HTML element is empty using jQuery? however that has not worked so far.
Any suggestions for a noob idiot? Appreciation for all responses in advance.
<button onclick="popup()">text</button>
<script>
var box = document.getElementById('popupbox');
function popup(){
box.style.display = "block";
var content = document.createElement('div');
content.className = 'boxstyle';
content.innerHTML = ' ...a handful of tags...';
box.appendChild(content);}
function exit(){
box.style.display = "none";}
</script>
You can create a popup using a modal as follows. I just copied code from here
<!DOCTYPE html>
<html>
<head>
<style>
/* 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>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// 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";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.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";
}
}
</script>
</body>
</html>
I actually managed to solve it by simply tossing in box.innerHTML = '' right after the block appears so that it has a clean slate to work with. I was trying to go a little more elegant and seeking to use an If/Else statement but in the end it seems to work. Much appreciation for all who answered / commented, you all are awesome!
<button onclick="popup()">text</button>
<script>
var box = document.getElementById('popupbox');
function popup(){
box.style.display = "block";
box.innerHTML = '';
var content = document.createElement('div');
content.className = 'boxstyle';
content.innerHTML = ' ...a handful of tags...';
box.appendChild(content);}
function exit(){
box.style.display = "none";}
Basically i tried creating a modal box that will appear after clicking a button for submission. It will either display upload successful or upload failed. Now, I have two problems that i have encountered that i am hoping that you guys can help me out. Here are the questions:
After clicking the submit button, it will appear roughly for 3 seconds and then it will postback. After that, the modal box is gone. What i want to happen is, the modal box should not disappear unless i clicked the x button. Then after that, the webpage can now do postback. If possible, how to achieve this?
Also, i have noticed that the modal box that i have integrated in my website cannot distinguish if the upload is successful or fail. I can see that it will still display upload successful even if the submission is failed. As of now, I have only coded the upload successful because I don't know yet on how to apply the upload fail yet. It should be able to determine if the submit button is successful or failed. How to achieve this?
Here is the aspx and script:
<asp:Button ID="Button1" runat="server" CssClass="submitButton" Text="Save
Item" OnClick="Button1_Click"/>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Upload Successful</p>
</div>
</div>
<script>
var modal = document.getElementById('myModal');
var btn = document.getElementById('<%=Button1.ClientID%>');
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>
Here is the code-behind. Take note, i haven't really put anything inside the catch because its suppose to return an upload failed popup box:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
int item_brandId =
ConnectionClassBrands.GetIdByBrand(itemBrand.Text);
string item_model = itemModel.Text;
double item_price = Convert.ToDouble(itemPrice.Text);
string item_image1 = Session["PicturePath1"].ToString();
string item_image2 = Session["PicturePath2"].ToString();
string item_description = itemDescription.Text;
string item_necktype = itemNeckType.Text;
string item_body = itemBody.Text;
string item_fretboard = itemFretboard.Text;
string item_fret = itemFret.Text;
string item_bridge = itemBridge.Text;
string item_neckpickup = itemNeckPickup.Text;
string item_bridgepickup = itemBridgePickup.Text;
string item_hardwarecolor = itemHardwareColor.Text;
if (itemType1.Checked)
{
int item_type =
ConnectionClassBrands.GetIdByType(itemType1.Text);
ItemType = item_type;
}
else if (itemType2.Checked)
{
int item_type =
ConnectionClassBrands.GetIdByType(itemType2.Text);
ItemType = item_type;
}
var item = new instrumentItem
{
typeId = ItemType,
brandId = item_brandId,
model = item_model,
price = item_price,
itemimage1 = item_image1,
itemimage2 = item_image2,
description = item_description,
necktype = item_necktype,
body = item_body,
fretboard = item_fretboard,
fret = item_fret,
bridge = item_bridge,
neckpickup = item_neckpickup,
bridgepickup = item_bridgepickup,
hardwarecolor = item_hardwarecolor
};
ConnectionClassGuitarItems.AddStringInstrumentItems(item);
ClearTextFields2();
}
catch (Exception)
{
}
}
Here is the stylesheet if necessary:
.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;
}