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?
Modals do not exist in JavaScript or HTML standard. In order to define the concept, you have two options:
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:
<body> level or at .modal-body level)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.
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">👍🏽 Received.</dialog>
If someone can provide a solution with less code (and for multiple ids), for the same result with no dependencies, please be my guest; I would love to learn.