<dialog id="dialog">
<button id="closeBtn" class="btn">X</button>
<form id="form" method="dialog">
<label>
First Name
<input name="firstName" />
</label>
<label>
Second Name
<input name="secondName" />
</label>
<button class="btn" type="submit" value="submit">Submit</button>
</form>
</dialog>
<button id="showBtn">Show Modal</button>
<p id="details"></p>
html, body {
height: 100%;
margin: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
#dialog input, #dialog label {
display: block;
}
#dialog input {
width: 30ch;
}
#dialog label {
margin-block-start: 10px;
margin-block-end: 10px;
}
.btn {
margin-left: auto;
display: block;
}
const dialog = document.getElementById('dialog');
const closeBtn = document.getElementById('closeBtn');
const showBtn = document.getElementById('showBtn');
const form = document.getElementById('form');
const details = document.getElementById('details');
const inputs = document.querySelectorAll('form input');
closeBtn.addEventListener('click', () => {
dialog.close();
});
showBtn.addEventListener('click', () => {
dialog.showModal();
});
dialog.onclose = () => {
console.log(dialog.returnValue)
if (dialog.returnValue === 'submit') {
let info = '';
const formData = new FormData(form)
for(let pair of formData.entries()) {
info += pair[1] + ' ';
};
details.innerText = info;
}
form.reset();
dialog.returnValue = '';
};
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.