When a visitor checks the checkbox, 2 other inputs are displayed. When the visitor unchecks the checkbox, I want the input values reset and the inputs to NOT be displayed.
if (selectpmCryptoCurrency.value=='on') {/* ... */}
you have to check
if (selectpmCryptoCurrency.checked) {/* ... */}
PS: We can’t see your HTML code if you don’t format it as code (e.g. using the </> button in the comment box). This also make it more readable anyway. :-)
Thanks, That worked to hide the elements.
I’ll edit my original post to display the html. I tried usine the </> but apparently didn’t do something correctly.
Sally
You got the transactions input ID wrong – in the HTML it’s InPmtMethod_CryptoCurrencyINP, in the JS InPmtMethodTxns_CryptoCurrencyINP. BTW you can see such errors in console of your browser dev tools:
Uncaught TypeError: Cannot set property ‘value’ of null
Thank you.
This is just 1 of 6 types of transactions the form asks people about. For that reason the form reset won’t work for this purpose.
Would I create a function () for each of my txn types or can I use an array?
It would certainly make sense to abstract away that functionality, for example using data attributes:
HTML
<div>
<label>
<input type="checkbox" data-toggle="foo">
Toggle "foo"
</label>
</div>
<div id="foo" class="hidden">
<label>
The foo value
<input value="foo">
</label>
</div>
<div>
<label>
<input type="checkbox" data-toggle="bar">
Toggle "bar"
</label>
</div>
<div id="bar" class="hidden">
<label>
The bar value
<input value="bar">
</label>
<label>
The other bar value
<input value="baz">
</label>
</div>
JS
var toggleBoxes = document.querySelectorAll('[data-toggle]')
var restoreDefault = function (element) {
element.value = element.defaultValue
}
toggleBoxes.forEach(function (toggleBox) {
// Get the element that should be toggled...
var toggleTarget = document.getElementById(toggleBox.dataset.toggle)
// ... and the input elements it contains
var containedInputs = toggleTarget.querySelectorAll('input')
toggleBox.addEventListener('click', function () {
if (toggleBox.checked) {
// Show the target element
toggleTarget.style.display = 'block'
} else {
// Hide the target element
toggleTarget.style.display = 'none'
// Reset the values of all contained input elements
// to their default values (i.e. their `value` attribute)
containedInputs.forEach(restoreDefault)
}
})
})
(Storing those relations in the JS would be possible too, but it’s better to keep the JS as agnostic as possible as to how the markup looks like.)
I’ll play with this and come back with future questions.
This is the first survey for this group but I have other sites and forms that will certainly benefit from all I’ve picked up (and learned) today.
Thanks,
Sally