Small interactions can make a webpage easier to use: opening a tip, changing a setting, or reusing an interface component.
What You Need to Know
When a dialog form uses method=dialog, submitting can close the dialog and set its returnValue. That result is local to the page unless your script explicitly sends data elsewhere.
Try the Example
Take a look at the example. We’ll explain the important lines right below it.
<button type="button" id="open-dialog">Open choices</button>
<dialog id="choices-dialog">
<form method="dialog">
<button value="save">Save</button>
<button value="cancel">Cancel</button>
</form>
</dialog>
<script>
const choicesDialog = document.querySelector("#choices-dialog");
document.querySelector("#open-dialog").addEventListener("click", () => choicesDialog.showModal());
choicesDialog.addEventListener("close", () => console.log(choicesDialog.returnValue));
</script>
Let’s Read the Code
- value: The value is the actual data associated with a control or choice.
- <button>: The button offers an action; its type or command determines what happens.
- <dialog>: Dialog provides a browser-managed dialog container; modal display may need showModal or a supported command.
- type: Type changes what sort of control or resource the browser uses.
Read the named elements and attributes together. They explain how the browser connects this feature to the rest of the page.
What Happens in the Browser?
When this example includes JavaScript, it supplies behavior that ordinary HTML does not automatically provide. Always think about a fallback.
What makes it interactive? Look for the JavaScript that finds an element and reacts to an event. HTML provides the initial controls and content; the script updates the page. Try removing the script to see which part still works natively.
Your Turn
Run this on a local development server if it loads modules or resources. Change the visible text or trigger and check what still works with scripts disabled.
Common Beginner Mistakes
- Assuming new HTML syntax works in every browser without testing.
- HTML supplies structure; JavaScript is necessary for the scripted behavior in this example. Check keyboard access and focus movement too.
Key Takeaways
- When a dialog form uses method=dialog, submitting can close the dialog and set its returnValue.
- value: The value is the actual data associated with a control or choice.
- Remember that HTML form rules help the visitor, but server-side code must decide whether received data is valid.