编写表格的正确方法。
const
myForm = document.forms['my-form'] // All element's form parent.
, prices =
{ diamondsize : { '1ct': 450, '2ct':1000, '3ct':1500 }
, chainlength : { '16in': 1600, '18in':1800, '20in':2000, '22in':2200 }
, metal : { 'ag925': 299, 'au18':2999, 'pl950':1999, 'pd950':2999 }
};
myForm.oninput = updateTotalPrice; // for any input elements change
myForm.onreset = () =>
{
myForm.totalPrice.textContent = 0;
// ^-- use forms names
}
myForm.onsubmit = e =>
{
e.preventDefault(); // disable submit for testing.
updateTotalPrice();
console.log( 'result -> ', JSON.stringify( Object.fromEntries( new FormData( myForm ))));
setTimeout( console.clear, 7000);
}
function updateTotalPrice()
{
let total = 0
, entries = Object.fromEntries( new FormData( myForm )) // get all inputs values
;
for (let key in entries)
total += prices[key][entries[key]];
myForm.totalPrice.textContent = total;
}
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 16px;
}
fieldset {
margin : 1em;
padding : 1em;
width : 44em;
min-width : 44em;
}
legend {
padding: 0 .5em;
}
label {
margin : .4em 1em .3em .5em;
}
span[data-circle]::before {
box-sizing : border-box;
display : inline-block;
content : '';
border : 1px solid black;
border-radius : 50%;
margin-left : .5em;
}
span[data-circle="30"]::before { width : 30px; height : 30px; }
span[data-circle="40"]::before { width : 40px; height : 40px; }
span[data-circle="50"]::before { width : 50px; height : 50px; }
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
.as-console-row-code { background-color: yellow;}
<form name="my-form">
<fieldset>
<legend>Diamond size</legend>
<label>
<input type="radio" name="diamondsize" value="1ct" required>
1 ct
<span data-circle="30"></span>
</label>
<label>
<input type="radio" name="diamondsize" value="2ct">
2 ct
<span data-circle="40"></span>
</label>
<label>
<input type="radio" name="diamondsize" value="3ct">
3 ct
<span data-circle="50"></span>
</label>
</fieldset>
<fieldset>
<legend>Length</legend>
<label>
<input type="radio" name="chainlength" value="16in" required>
16 inch: neckline
</label>
<label>
<input type="radio" name="chainlength" value="18in">
18 inch: collarbone
</label>
<label>
<input type="radio" name="chainlength" value="20in">
20 inch: collar to bust
</label>
<label>
<input type="radio" name="chainlength" value="22in">
22 inch: bust
</label>
</fieldset>
<fieldset>
<legend>Metal</legend>
<label>
<input type="radio" name="metal" value="ag925" required>
Silver 925
</label>
<label>
<input type="radio" name="metal" value="au18">
Gold 18K
</label>
<label>
<input type="radio" name="metal" value="pl950">
Platinum 950
</label>
<label>
<input type="radio" name="metal" value="pd950">
Palladium 950
</label>
</fieldset>
<br> <br>
Total Price : <output name="totalPrice">0</output>
<br> <br>
<button type="submit">submit</button>
<button type="reset">Reset</button>
</form>