Donation Payment Amount Fields
Forms that ask for contributions to help with website maintenance sometimes have amounts you can select and also a field where you can type in an alternate amount. The Wordpreneur Cafe page is an example.
What happens when both 5.00 is selected and 12.00 is written in the alternate amount field?
The software that handles the form submission can decide which to honor, the 5.00 or the 12.00, assuming it is programmed to make such a decision. Alternatively, JavaScript can make the decision before the form is submitted.
Here, I will show you how to use JavaScript for the decision.
The example form has a dropdown with amounts to select. Below the dropdown is a field for typing in an alternate amount.
Here is the source code for the above two fields. The JavaScript is marked with the color blue.
<!-- select field for dropdown --> <select id="dropdown" onchange="document.getElementById('writein').value=''" name="selected_amount"> <option value="0">- Amounts -</option> <option value="3.00">3.00</option> <option value="5.00">5.00</option> <option value="10.00">10.00</option> <option value="15.00">15.00</option> </select> <!-- text field for alternate amount --> <input id="writein" onkeyup="document.getElementById('dropdown').options.selectedIndex=0" type="text" name="writin_amount" inputmode="numeric" pattern="[\d\.]*" title="Only numbers and periods; no $ symbol." style="width:90px;">
Each of the fields has an id value. And, each of the fields has JavaScript to remove any amount from the other field.
The dropdown's id value is dropdown
and the text field's value is writein
.
When a selection is made in the dropdown, theonchange=
JavaScript removes any content from the text field.
When the text field is typed into, theonkeyup=
JavaScript sets the dropdown to the first element, which has no amount specified.
No separate JavaScript section needs to be written. It is all in the onchange
attribute of the select
field and the onkeyup
attribute of the input
text field.
Use the example to enable your own forms when only one of two or more amount fields are allowed to contain a value.
(This content first appeared in Possibilities newsletter.)
Will Bontrager