I am learning Javascript and have studied these similar cases 1, 2, 3, 4, 5, 6, 7, 8 with no success. I don't use dependencies like jQuery or Bootstrap.
I want to replace alert("Success!"); with something like document.getElementById('modal-team').showModal(); in the below code, to show a modal and keep the user in the same page:
window.addEventListener("load", function() {
const form =
document.getElementById('registration');
form.addEventListener("submit", function(e) {
e.preventDefault();
const data = new FormData(form);
const action = e.target.action;
fetch(action, {
method: 'POST',
body: data,
})
.then(() => {
alert("Success!");
})
});
});
Can you please assist?
CodePudding user response:
Modals do not exist in JavaScript or HTML standard. In order to define the concept, you have two options:
- you create it yourself
- you load one particular implementation from a library which defines it in a particular way.
The questions listed above are using Bootstrap's implementation of modals and therefore would only be applicable if you used Bootstrap.
A modal is not particularly difficult to implement without a library, but you have to consider solving a few problems:
- how it displays on all devices, including mobile devices
- how it scrolls when its contents exceed the screen size (if you implement scrolling at
<body>
level or at.modal-body
level) - how you handle multiple modal instances (when you open a modal from another modal, do you keep them both open or do you close the initial modal)
- if (and how) you allow data injection into the modal instance and if (and how) you allow data injection back from the modal instance, when the modal gets closed (typically solved by specifying a callback which gets called by the modal, before it closes).
All of the above are already solved in most modal implementations, which is why people prefer using them, rather than writing their own.
To answer your specific question, an HTMLDivElement
does not have a .showModal()
method. Before you could call such a method, you first need to define it.
CodePudding user response:
I figure it out using a different path, but using more code which I don't like.
Used the same js to intercept (just removed .then):
window.addEventListener("load", function() {
const t = document.getElementById("infobar");
t.addEventListener("submit", function(e) {
e.preventDefault();
const n = new FormData(t),
o = e.target.action;
fetch(o, {
method: "POST",
body: data, }) }) });
Call an onsubmit function for a form with a unique id:
<form onsubmit="Dia()" id="infobar" name="form"
method="post" action="blablabla">
<input type="email" name="Email" placeholder="Email here">
<input type="submit" value="Join"></form>
The js function that serves the form:
function Dia(){document.getElementById("Di").showModal()};
The modal that is showed by the js function (used the dialog since it's supported by modern browsers 1):
<dialog id="Di">