JSFiddle - React, Tailwind, and code Playground
by Avi Algaly
HTML
<!-- A modal dialog containing a form -->
<dialog id="favDialog">
<form>
<p>
<label>Favorite animal:
<select>
<option value="default">Choose…</option>
<option>Brine shrimp</option>
<option>Red panda</option>
<option>Spider monkey</option>
</select>
</label>
</p>
<div>
<button value="cancel" formmethod="dialog">Cancel</button>
<button id="confirmBtn" value="default">Submit</button>
</div>
</form>
</dialog>
<p>
<button id="showDialog">Show the dialog</button>
</p>
<output></output>
CSS
dialog {
z-index: 10;
margin-top: 10px;
background: green;
border: none;
border-radius: 1rem;
}
JavaScript
const showButton = document.getElementById('showDialog');
const favDialog = document.getElementById('favDialog');
const outputBox = document.querySelector('output');
const selectEl = favDialog.querySelector('select');
const confirmBtn = favDialog.querySelector('#confirmBtn');
// "Show the dialog" button opens the <dialog> modally
showButton.addEventListener('click', () => {
favDialog.showModal();
});
// "Favorite animal" input sets the value of the submit button
selectEl.addEventListener('change', (e) => {
confirmBtn.value = selectEl.value;
});
// "Confirm" button triggers "close" on dialog because of [method="dialog"]
favDialog.addEventListener('close', (e) => {
outputBox.value = favDialog.returnValue === 'default' ? "No return value." : `ReturnValue: ${favDialog.returnValue}.`; // Have to check for "default" rather than empty string
});
confirmBtn.addEventListener('click', (event) => {
event.preventDefault(); // We don't want to submit this fake form
favDialog.close(selectEl.value); // Have to send the select box value here.
});