I want to avoid using a for loop to validate a set of radio buttons. I know that its possible to use their boolean value to do this I just cannot seem to execute it. Is there a better way to do this?
Here are my buttons:
<form method="post" name="newUser" onsubmit="return proc()">
First name:<br />
<input type="text" id="fName" /><br />
<div id="first_name_error"></div>
Last name:<br />
<input type="text" name="lName" /><br />
<div id="last_name_error"></div>
E-mail address:<br />
<input type="text" name="eMail" /><br />
<div id="email_error"></div>
Gender:<input type="radio" name"sex" value="male" />Male
<input type="radio" name="sex" value="female" />Female<br />
<div id="gender_error"></div>
Here is my JS:
function proc(){
var errmsg = "";
if (document.forms["newUser"]["fName"].value == "")
{
document.getElementById('first_name_error').innerHTML = "*This field is required";
document.getElementById('first_name_error').style.color = "red";
}
if (document.forms["newUser"]["lName"].value == "")
{
document.getElementById('last_name_error').innerHTML = "*This field is required";
document.getElementById('last_name_error').style.color = "red";
}
if (document.forms["newUser"]["eMail"].value == "")
{
document.getElementById('email_error').innerHTML = "*This field is required";
document.getElementById('email_error').style.color = "red";
}
if (document.forms["newUser"].sex == false)
{
document.getElementById('gender_error').innerHTML = "*Please select gender";
document.getElementById('gender_error').style.color = "red";
}
return false;
}
I think you'd better assign two ids to two radio buttons (radbtnMale, radbtnFemale for example)
Then check:
if (document.getElementById("radbtnMale").checked == false && document.getElementById("radbtnFemale").checked == false) {
document.getElementById('gender_error').innerHTML = "*Please select gender";
document.getElementById('gender_error').style.color = "red";
} else {
//
}
Try this (jQuery):
if($('input[name=n]:checked').length==0){
//error
}else{
//OK
}
Related
I have a HTML5 form and I'm using javascript to validate the form.
I have several 'if's checking the form and if it valid they change a variable ('pass') to true or false. They also display an error message. The problem is that even if just one thing is valid it changes the variable is true and I need it to only make pass true if everything else is valid.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<div>
<form name="register" action="register.php" method="POST" >
<label>First Name:</label>
<input type="text" id="firstName" name="firstName"><br />
<label id="warning_first"></label>
<br />
<label>Surname:</label>
<input type="text" id="lastName" name="lastName"><br />
<label id="warning_second"></label>
<br />
<label>Gender:</label>
<input type="radio" name="gender" value="Male" id="male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Other">Other
<input type="radio" name="gender" value="Prefer not to say"> Prefer not to say <br />
<label id="warning_third"></label>
<br />
<label>Email:</label>
<input type="email" id="email" name="email"> <br />
<label id="warning_fourth"></label>
<br />
<label>Confirm Email:</label>
<input type="email" id="confirmEmail" name="confirmEmail">
<br />
<label>Mobile:</label>
<input type="tel" id="mobileNumber" name="mobileNumber">
<br />
<label>Telephone:</label>
<input type="tel" id="telephoneNumber" name="telephoneNumber">
<br />
<input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
<input type="button" name="submit" value="Register" onclick="submitCheck();">
</form>
<script src="script.js"></script>
</div>
</body>
</html>
My JavaScript:
function submitCheck() {
var pass = false;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var genderTest = document.getElementsByName("gender");
var genderIf = false;
for (var a = 0; a < genderTest.length; a += 1) {
if (genderTest[a].checked) {
genderIf = true;
}
}
var emailCheck = document.getElementById("email").value;
if (firstName.length > 0) {
document.getElementById("warning_first").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_first").innerHTML = "This is required!";
pass = false;
}
if (lastName.length > 0) {
document.getElementById("warning_second").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_second").innerHTML = "This is required!";
pass = false;
}
if (genderIf) {
document.getElementById("warning_third").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_third").innerHTML = "This is required!"
pass = false;
}
if (emailCheck.length > 0) {
document.getElementById("warning_fourth").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_fourth").innerHTML = "Your email is too short!";
pass = false;
}
if (pass) {
console.log("OK");
} else {
console.log("NO");
}
}
As you can see, if the email is true, the console will log "OK" (which I am using to see if everything is valid"). How can I solve this so that it doesn't 'pass' to true if just the email is valid?
I am using a normal button instead of a submit button because of issues with the #onsubmit.
At the moment, you default pass to false and change it to true if any element passes the test.
Reverse your logic.
Set the default value of pass to true. Change it to false if any element fails its test.
Its simple, at the start of your code change your pass variable to have a value of 1 like so:
var pass = 1;
Now change the line of code in your IF statements where you have your pass variable. For a true condition set to this:
pass *= 1;
And for a false condition to this
pass *= 0;
This ensures that unless all IF conditions are satisfied your pass variable will not return a true state.
I have tried and tried and cannot figure out why when I submit this form it will not activate the javascript function Validate().
This is nearly an exact replica of another form with namely one change: I've added a textarea and removed some check boxes.
I could really use some help troubleshooting this thing...
<div id="MainDivDomID">
<h1>Send us a message</h1>
<form id="contactForm" action="#" enctype="multipart/form-data" data-ajax="false" method="post" onsubmit="return Validate()">
<input name="Source" type="hidden" value="web" />
<input name="FormID" type="hidden" value="af3031b7-8f0e-433d-b116-6f10f0f231df" />
<div class="halves">
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_First" type="text" value="" placeholder="First Name" />
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_Last" type="text" value="" placeholder="Last Name" />
</div>
<div class="halves">
<input maxlength="255" name="463a05a6-e700-462d-b43d-0ef5cb793f11" type="text" value="" placeholder="Email" />
<input name="eae1ba0e-a5b4-423b-985c-dc36a73c45c5" type="text" placeholder="Phone Number" />
</div>
<textarea maxlength="255" name="b60680e4-3e46-43a5-b4e8-a21c6363ea0c" placeholder="Message"></textarea>
<input name="CaptchaAnswer" type="text" placeholder="Please answer the math question..." />
<img src="https://my.serviceautopilot.com/images/security-question.jpg" alt="" />
<p>
<button id="submitButtonText" class="et_pb_button et_pb_bg_layout_dark">Send Message</button>
</p>
</form>
</div>
function Validate() {
var IsValidated = true;
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_Last')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your last name.");
}
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = document.getElementsByName('017b9b5e-5595-4b74-97a2-187f45400b34')[0].value;
if (email == "" || re.test(email) != true) {
IsValidated = false;
alert("Please fill in your email address.");
}
if (document.getElementsByName('4a6b6e47-2fac-4cb4-8ca0-e4a3db4c7fc0')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in your phone number.");
}
if (document.getElementsByName('b60680e4-3e46-43a5-b4e8-a21c6363ea0c')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in a message.");
}
if (document.getElementsByName('CaptchaAnswer')[0].value != "8") {
IsValidated = false;
alert("Please answer the math question.");
}
if (IsValidated == true) {
document.getElementById("contactForm").submit();
} else {
alert("Please fill out all fields.");
return false;
}
}
function CreateEntity() {
document.getElementById("submitButtonText").value = "create";
Validate();
}
There is an exception at the line of code
document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == ""
Dont have any name a7aa41d9-b309-48d7-af97-5a2ce65eb850_First in your document, so that the [0] is undefined.
If you change from
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
to
if (document.getElementsByName('be9953c9-471c-42f4-a1cf-524f5b67fc38_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
The message Please fill out your first name will shown.
You need to prevent the default behavior using e.preventDefault(); otherwise it will try to submit the form
function Validate(e) {
e.preventDefault();
var IsValidated = true;
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_First')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your first name.");
}
if (document.getElementsByName('a7aa41d9-b309-48d7-af97-5a2ce65eb850_Last')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill out your last name.");
}
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = document.getElementsByName('017b9b5e-5595-4b74-97a2-187f45400b34')[0].value;
if (email == "" || re.test(email) != true) {
IsValidated = false;
alert("Please fill in your email address.");
}
if (document.getElementsByName('4a6b6e47-2fac-4cb4-8ca0-e4a3db4c7fc0')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in your phone number.");
}
if (document.getElementsByName('b60680e4-3e46-43a5-b4e8-a21c6363ea0c')[0].value.trim() == "") {
IsValidated = false;
alert("Please fill in a message.");
}
if (document.getElementsByName('CaptchaAnswer')[0].value != "8") {
IsValidated = false;
alert("Please answer the math question.");
}
if (IsValidated == true) {
document.getElementById("contactForm").submit();
} else {
alert("Please fill out all fields.");
return false;
}
}
function CreateEntity() {
document.getElementById("submitButtonText").value = "create";
Validate();
}
<div id="MainDivDomID">
<h1>Send us a message</h1>
<form id="contactForm" action="#" enctype="multipart/form-data" data-ajax="false" method="post" onsubmit="return Validate(event)">
<input name="Source" type="hidden" value="web" />
<input name="FormID" type="hidden" value="af3031b7-8f0e-433d-b116-6f10f0f231df" />
<div class="halves">
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_First" type="text" value="" placeholder="First Name" />
<input name="be9953c9-471c-42f4-a1cf-524f5b67fc38_Last" type="text" value="" placeholder="Last Name" />
</div>
<div class="halves">
<input maxlength="255" name="463a05a6-e700-462d-b43d-0ef5cb793f11" type="text" value="" placeholder="Email" />
<input name="eae1ba0e-a5b4-423b-985c-dc36a73c45c5" type="text" placeholder="Phone Number" />
</div>
<textarea maxlength="255" name="b60680e4-3e46-43a5-b4e8-a21c6363ea0c" placeholder="Message"></textarea>
<input name="CaptchaAnswer" type="text" placeholder="Please answer the math question..." />
<img src="https://my.serviceautopilot.com/images/security-question.jpg" alt="" />
<p>
<button type='submit' id="submitButtonText" class="et_pb_button et_pb_bg_layout_dark">Send Message</button>
</p>
</form>
</div>
I am new to .asp and Javascript and wondered if someone was able to advise how to show validation errors for fields below the form in a single table or text field rather than using alerts. Alerts and validation are working.
Here is the table that i plan to put the validation errors into:
<asp:Table ID="StatusTable"
runat="server" Width="100%"><asp:TableRow ID="StatusRow" runat="server">
<asp:TableCell ID="StatusTextCell" runat="server" Width="95%">
<asp:TextBox ID="StatusTextBox" runat="server" Width="100%" />
</asp:TableCell><asp:TableCell ID="StatusPadCell" runat="server" Width="5%">
</asp:TableCell></asp:TableRow></asp:Table>
And here is an example of some the Javascript I am using where i need the validation error messages to show in the table rather than from alerts.
Would be extremely grateful for any advise
< script type = "text/javascript"
language = "Javascript" >
function RequiredTextValidate() {
//check all required fields from Completed Table are returned
if (document.getElementById("<%=CompletedByTextBox.ClientID%>").value == "") {
alert("Completed by field cannot be blank");
return false;
}
if (document.getElementById("<%=CompletedExtTextBox.ClientID %>").value == "") {
alert("Completed By Extension field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNoTextBox.ClientID %>").value == "") {
alert("Employee No field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNameTextBox.ClientID %>").value == "") {
alert("Employee Name field cannot be blank");
return false;
}
return true;
}
< /script>
function ValidateFields() {
//Validate all Required Fields on Form
if (RequiredTextValidate() && CheckDate(document.getElementById("<%=SickDateTextBox.ClientID%>").value) && CheckTime(this) && ReasonAbsent() && ReturnDateChanged() && FirstDateChanged() && ActualDateChanged() == true) {
return true;
}
else
return false;
}
There are many ways that this type of thing can be done, here is one way which I have put together based on what you have so far...
http://jsfiddle.net/c0nh2rke/
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
HTML
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
Script
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
The best JavaScript is no JavaScript.
To that end, consider:
<form action="javascript:alert('Submitted!');" method="post">
<input type="text" name="someinput" placeholder="Type something!" required />
<input type="submit" value="Submit form" />
</form>
Notice how the browser will render native UI to show that the field was left blank? This is by far the best way to do it because it doesn't rely on JavaScript. Not that there's anything wrong with JS, mind, but far too often a single typo in form validation code has caused hours of debugging!
Can someone help me make this alert look much nicer? Like Maybe split up Each text box on its own line? I can not figure out how to make this look a lot cleaner and not just all piled on one line.
To see alert hit Lien radio button and then hit next without filling textboxes
http://jsfiddle.net/t4Lgm0n2/9/
function validateForm(){
var QnoText = ['lien']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'lname';
var eD = "";
if (CkStatus && document.getElementById(ids).value == '') {
eD = eD+' lienholder name';
document.getElementById(ids).focus();
flag = false;
}
ids2 = QnoText[i]+'laddress';
if (CkStatus && document.getElementById(ids2).value == '') {
eD=eD+' lienholder address';
document.getElementById(ids2).focus();
flag = false;
}
ids3 = 'datepicker2';
if (CkStatus && document.getElementById(ids3).value == '') {
eD=eD+' lien date';
document.getElementById(ids3).focus();
flag = false;
}
if(eD!="") alert("Please enter "+eD);
}
return flag;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" value="Yes" name="lien" id="lien" required="yes" onchange="showhideForm(this.value);"/><label for="lien">Lien</label>
<input type="radio" value="None" name="lien" id="nolien" onchange="showhideForm(this.value);"/><label for="nolien">No Lien</label>
<script type="text/javascript">
function showhideForm(lien) {
if (lien == "Yes") {
document.getElementById("div1").style.display = 'block';
document.getElementById("div2").style.display = 'none';
}
else if (lien == "None") {
document.getElementById("div2").style.display = 'block';
document.getElementById("div1").style.display = 'none';
$("#div1 > .clearfix input:text").val("");
}
}
</script>
<div id="div1" style="display:none">
<div class="clearfix">
<label for="lname">Lienholder Name:</label>
<input type="text" name="lienlname" validateat="onSubmit" validate="maxlength" id="lienlname" size="54" maxlength="120" message="Please enter lienholder name." value="">
</p>
<p>
<label for="laddress">Lienholder Address:</label>
<input type="text" name="lienladdress" validateat="onSubmit" validate="maxlength" id="lienladdress" size="54" maxlength="120" message="Please enter lienholder address." value="">
</p>
<p>
<label for="ldate">Date of Lien:</label>
<input type="text" name="lienldate" id="datepicker2" mask="99/99/9999" value="">
</div>
</div>
<div id="div2" style="display:none">
<!---You are not qualified to see this form.--->
</div>
<input type="submit" name="submit" value="Next" onclick="validateForm()">
You can use new line characters \n to make text more readable:
var eD = [];
if (CkStatus && document.getElementById(ids).value == '') {
eD.push('Please enter lienholder name');
document.getElementById(ids).focus();
flag = false;
}
// ...
if (eD.length) alert(eD.join('\n'));
As you can see I'm also pushing error messages into ed array, which makes it more convenient to concatenate resulting message using .join() method.
Demo: http://jsfiddle.net/t4Lgm0n2/11/
bit of a noob with form validation. I'm trying to get this form to validate on the required fields, and something's amiss. Here's what I'm working with:
html:
<form action="../visit/thankyou.html" method="post" id="vsurvey">
<input type="hidden" name="id" value="503" />
<fieldset>
<legend>Group and Coordinator Information</legend>
<label><span>Group Leader Name<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8149" />
</label>
<label><span>Email<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8155" />
</label>
<label><span>Phone<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8156" />
</label>
<label><span>School/Organization<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8159" />
</label>
<label><span>Program</span>
<input type="text" name="question_8180" />
</label>
<label><span>Grade(s)</span>
<input type="text" name="question_8181" />
</label>
<label><span>Number of Participants<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8182" />
</label>
</fieldset>
<fieldset>
<label><span>Preferred Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8185" name="question_8185" />
</label>
<label><span>Second Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8186" name="question_8186" />
</label>
<label><span>Third Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8187" name="question_8187" />
</label>
<label>Special Accommodations
<input type="text" name="question_8174" />
</label>
</fieldset>
<label>What is the purpose or desired outcome of this visit?
<textarea name="question_13026"></textarea>
</label>
<label>How did you learn about our Group Visit Program?
<textarea name="question_8176"></textarea>
</label>
<label>Comments
<textarea name="question_8184"></textarea>
</label>
<input type="submit" id="sbutton" value="Submit Request" />
</form>
js:
function validateForm() {
var x = document.forms["vsurvey"]["question_8149"].value;
if (x == null || x == "") {
alert("Please fill in the Group Leader's name.");
return false;
}
var x = document.forms["vsurvey"]["question_8155"].value;
if (x == null || x == "") {
alert("Please fill in the email field.");
return false;
}
var x = document.forms["vsurvey"]["question_8156"].value;
if (x == null || x == "") {
alert("Please fill in the phone field.");
return false;
}
var x = document.forms["vsurvey"]["question_8159"].value;
if (x == null || x == "") {
alert("Please fill in the School/Organization field.");
return false;
}
var x = document.forms["vsurvey"]["question_8182"].value;
if (x == null || x == "") {
alert("Please indicate the number or participants.");
return false;
}
var x = document.forms["vsurvey"]["question_8185"].value;
if (x == null || x == "") {
alert("Please enter your preferred date.");
return false;
}
var x = document.forms["vsurvey"]["question_8186"].value;
if (x == null || x == "") {
alert("Please enter your second date preference.");
return false;
}
var x = document.forms["vsurvey"]["question_8187"].value;
if (x == null || x == "") {
alert("Please enter your third date preference.");
return false;
}
}
http://jsfiddle.net/blackessej/9a6BJ/1/
Currently the form submits the info anyway, but without sending the user to the thankyou page, if all required fields aren't filed in. If all required fields are filed, the thankyou page gets called.
You're not calling validatorForm. Your input button needs to be the following
<input type="submit" id="sbutton" value="Submit Request" onclick="return validateForm()" />
Or use the onsubmit event of your form
<form action="../visit/thankyou.html" method="post" id="vsurvey" onsubmit="return validateForm()">
You need to create an onSubmit event to call validateForm:
document.getElementById('vsurvey').onsubmit = validateForm;