JSFiddle - React, Tailwind, and code Playground
by Imri Paloja
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
<div class="container">
<input id="myText" type="text" value="Hello">
<button onclick="show()">Show value</button>
<form id="myForm">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="password" name="pwd" placeholder="Password">
<input type="number" name="age" placeholder="Age">
<input type="checkbox" name="subscribe" value="yes">
<input type="radio" name="gender" value="male">
<input type="radio" name="gender" value="female">
<select name="country">
<option value="us">USA</option>
<option value="ca">Canada</option>
</select>
<textarea name="notes"></textarea>
<button type="button" onclick="collect()">Collect values</button>
</form>
</div>
CSS
html, vody {
color: #454545;
}
.container {
margin-top: 5% !important;
}
input,select,textarea {
width: 100% !important;
margin: 20px 3px !important;
padding: 2px 3px;
}
JavaScript
function show() {
const txt = document.getElementById('myText').value;
console.log(txt); // → "Hello"
}
function collect() {
const form = document.getElementById('myForm');
const data = {};
// Loop over every form control
Array.from(form.elements).forEach(el => {
// Skip the button itself
if (el.type === 'button' || el.type === 'submit') return;
switch (el.type) {
case 'checkbox':
// For a single checkbox, store true/false
// For a group (same name), store an array of checked values
if (!data[el.name]) data[el.name] = [];
if (el.checked) data[el.name].push(el.value);
break;
case 'radio':
// Only store the selected radio button
if (el.checked) data[el.name] = el.value;
break;
case 'file':
// Files are accessed via the FileList object
data[el.name] = el.files; // (you’ll usually process these separately)
break;
default:
// Covers text, email, number, textarea, select‑one, etc.
data[el.name] = el.value;
}
});
console.log(data);
// Example output:
// {
// username: "alice",
// email: "[email protected]",
// pwd: "secret",
// age: "30",
// subscribe: ["yes"],
// gender: "female",
// country: "ca",
// notes: "Some notes…"
// }
}
const modify_form = document.getElementById("myForm");
modify_form.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(modify_form);
const modifiedValues = {};
for (const [name, value] of formData.entries()) {
const input = modify_form.querySelector(`input[name="${name}"]`);
if...