I am trying to have an error message displayed if I try to submit an empty form. the below code shows what SHOULD be happening.
function prepareEventHandlers() {
document.getElementById("frmContact").onsubmit = function () {
if (document.getElementById("email").value == '') {
document.getElementById("errorMessage").innerHTML = 'Please provide at least an email address!';
return false;
}
else {
document.getElementById("errorMessage").innerHTML = '';
return true;
}
};
}
window.onload = function () {
prepareEventHandlers();
}
Here is the code for my cshtml side of it:
<form id="frmContact" method="post">
<fieldset>
<legend>Personal Information</legend>
<p>email and other elements here.</p>
<div>
<input type="checkbox" name="checkbox1" checked="false" />
Remind me later <br />
</div>
<p><span id="errorMessage"></span></p>
<input type="submit" value="Send" id="send"/>
</fieldset>
</form>
<script src="http://localhost:53734/Scripts/JScript3.js"></script>
I tried debugging it, but it doesn’t call the prepareEventHandlers method on click. also, tried sticking the script tag above the form, but this didn’t do anything either.
Your form has no input element for the email. Your JavaScript is looking for an element with the ID of email (presumably an input) with
document.getElementById("email").valuebut your form is missing it.Change:
to:
And then your code works fine. jsFiddle example