I have been trying to use java script to validate a contact form. The idea is to add a paragraph tag above each textbox and when the submit button is clicked a javascript function should be fired. if the textbox is empty the "hidden" class will be removed from the class list of the paragraph so it will be visible The problem is that function is fired only once, the first time i click the button. but if I fill on textbox and click again the function is not fired. can any body help me about this? Note: if I use getElementById the function is not fired and the compiler goes to the server side function btnSubmit_Click but when using getElementByName the function is fired only once as described above.
<div id="contactForm" runat="server">
<div class="control-group form-group">
<div class="controls">
<p id="errname" class="hidden">You must insert your <b>name</b></p>
<input type="text" runat="server" class="form-control" id="txtname" name="txtname" placeholder="*Full Name" >
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<p id="erremail" class="hidden">You must insert your <b>email</b></p>
<input type="email" runat="server" class="form-control" id="txtemail" name="txtemail" placeholder="*Email" >
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<p id="errmessage" class="hidden">You must insert a <b>message</b></p>
<textarea runat="server" rows="10" cols="100" class="form-control" id="txtmessage" name="txtmessage" placeholder="*Message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return myfun();" OnClick="btnSubmit_Click" Text="Send Message" class="btn btn-primary btn-block" />
</div>
and the javascript function is:
function myfun() {
document.getElementById("errname").classList.add('hidden');
document.getElementById("erremail").classList.add('hidden');
document.getElementById("errmessage").classList.add('hidden');
var flag = true;
if (!document.getElementsById("txtname").value) {
document.getElementById("errname").classList.remove('hidden');
flag= false;
}
if (!document.getElementsById("txtemail").value) {
document.getElementById("erremail").classList.remove('hidden');
flag= false;
}
if (!document.getElementsById("txtmessage").value) {
document.getElementById("errmessage").classList.remove('hidden');
flag = false;
}
if (flag == false) { return false;}
}
</script>