I have been requested to create a simple form with JavaScript validation code. I have constructed the entire form and all of my validation scripting is working, however I have been asked to display any relevant errors in Span tags next to the appropriate field (as opposed to displaying alerts as I am used to doing).
I have been told to have a span tag next to each element like text input, radio button etc with the appropriate error text previously entered, and then style each span so that they are hidden. When the submit button is pressed, the script is supposed to change the style of the appropriate span to visible in order to display the text. I have written the code for this but the issue I am having is that my Span errors become visible, but almost instantly they disappear back to the hidden state. Is there any particular reason this could be happening?
Here’s some of my code.
HTML:
< input type="checkbox" name="agree"/> < span id="agreeSpan>Error text< /span>
CSS:
span {
color:red;
font-size:small;
visibility:hidden;
}
And the JavaScript:
function validateAgreement()
{
var agreeBox = document.registration.agree;
var agreeSpan = document.getElementById('agreeSpan');
if (!agreeBox.checked) {
agreeSpan.style.visibility = 'visible';
return false;
}
Am I missing something obvious? Is it possible that I am trying to style 1 specific span and that the styling attribute for the general span tags is overriding this particular one?
Thanks very much and apologies if this is a rookie question! I’m new to JS 🙂
To stop the submit happening, returning false there is not enough. It depends how you’re calling that function, which I imagine is something like this
Note the return. The on submit handler needs to be returning false, so you need to make sure to return whatever value your function returns. If you just did…
then your form will always get submitted.