Form not validating - javascript

Can someone tell me what I'm wrong with my code? It's not validating. When I hit the submit button, nothing happens. There's no error message that shows or pop up.
Here is the html of the form
<form name="summerForm" method="post" action="signup.html">
<h2>Programs</h2>
<p>Please select the following prgrams:</p>
<select name="programs">
<option value="beginningSpanish">Beginning Spanish</option>
<option value="advancedSpanish">Advanced Spanish</option>
<option value="conversationalSpanish">Conversational Spanish</option>
<option value="advancedConversationalSpanish">Advanced Conversational Spanish</option>
<option value="spanishGrammerAndComposition">Spanish Grammar and Composition</option>
<option value="culturalTreasuresOfMexico">Cultural Treasures of Mexico</option>
</select>
<h2>Parent's Information</h2>
<label for="firstName">First Name:</label>
<input type="text" id="pFirstName" name="pFirstName"/>
<label for="middleName">Middle Name:</label>
<input type="text" id="pMiddleName" name="pMiddleName"/>
<label for="lastName">Last Name:</label>
<input type="text" id="pLastName" name="LastName"/>
<br/>
<strong>Relationship to Child:</strong><br/>
<label for="nameFather">Father</label>
<input type="radio" id="pFather" name="relationship" value="Father"/>
<label for="nameMother">Mother</label>
<input type="radio" id="pMother" name="relationship" value="Mother"/>
<label for="nameGuardian">Guardian</label>
<input type="radio" id="pGuardian" name="relationship" value="Guardian"/>
<br/>
<label for="address1">Address</label>
<input type="text" id="pAddress" name="pAddress"/><br/>
<label for="city1">City</label>
<input type="text" id="pCity" name="pCity"/>
<label for="state1">State</label>
<input type="text" id="pState" size="2" maxlength="2" name="pState"/>
<label for="zipCode1">Zip Code</label>
<input type="text" size="5" maxlength="5" id="pZipCode" name="pZipCode"/><br/>
<label for="homePhone">Home Phone</label>
<input type="text" id="pHomePhone" name="pHomePhone"/>
<label for="cellPhone">Cell Phone</label>
<input type="text" id="pCellPhone" name="pCellPhone"/><br/>
<label for="emailAddress">Email Address:</label>
<input type="text" id="pEmailAddress" name="pEmailAddress"/>
<h2>Child's Information</h2>
<label for="cFirstName">First Name:</label>
<input type="text" id="cFirstName" name="cFirstName"/>
<label for="cMiddleName">Middle Name:</label>
<input type="text" id="cMiddleName" name="cMiddleName"/>
<label for="cLastName">Last Name:</label>
<input type="text" id="cLastName" name="cLastName"/><br/>
<label for="secondName">Name the child goes by:</label>
<input type="text" id="secondName" name="secondName"/><br/>
Photo of child. (recommended format: 400x400 .jpg)<br/>
<input type="file" name="photo"/><br/>
<strong>Gender:</strong><br/>
<label for="cMale">Male</label>
<input type="radio" id="cMale" name="sex" value="Male"/>
<label for="cFemale">Female</label>
<input type="radio" id="cFemale" name="sex" value="Female"/><br/>
<label for="cDOB">Date of Birth:</label>
<input type="date" id="cDOB" size="12" maxlength="10" placeholder="MM/DD/YYYY" name="cDOB"/><br/>
<label for="cMedical">Medical Conditions:</label><br/>
<textarea id="cMedical" name="comments"> </textarea><br/>
<label for="cSDR">Special Dietary Requirements:</label><br/>
<textarea id="cSDR" name="comments"> </textarea><br/>
<p><strong>Secondary Emergency Contact</strong></p>
First Name
<input type="text" name="sFirstName"/>
Last Name
<input type="text" name="sLastName"/>
Phone Number
<input type="text" name="sPhoneNumber"/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
Here is the Jquery/Javascript
$(document.ready( function() {
var errorStatusHandle = $('.errorMessage');
var elementHandle = new Array (15);
elementHandle[0] = $('[name="pFirstName"]');
elementHandle[1] = $('[name="pLastName"]');
elementHandle[2] = $('[name="pAddress"]');
elementHandle[3] = $('[name="pCity"]');
elementHandle[4] = $('[name="pState"]');
elementHandle[5] = $('[name="pZipCode"]');
elementHandle[6] = $('[name="pCellPhone"]');
elementHandle[7] = $('[name="pEmailAddress"]');
elementHandle[8] = $('[name="cFirstName"]');
elementHandle[9] = $('[name="cLastName"]');
elementHandle[10] = $('[name="secondName"]');
elementHandle[11] = $('[name="cDOB"]');
elementHandle[12] = $('[name="sFirstName"]');
elementHandle[13] = $('[name="sLastName"]');
elementHandle[14] = $('[name="sPhoneNumber"]');
function isValidData() {
if(isEmpty(elementHandle[0].val())) {
elementHandle[0].addClass("error");
errorStatusHandle.text("Please enter your first name.");
elementHandle[0].focus();
return false;
}
if(isEmpty(elementHandle[1].val())) {
elementHandle[1].addClass("error");
errorStatusHandle.text("Please enter your last name.");
elementHandle[1].focus();
return false;
}
if(isEmpty(elementHandle[2].val())) {
elementHandle[2].addClass("error");
errorStatusHandle.text("Please enter your address.");
elementHandle[2].focus();
return false;
}
if(isEmpty(elementHandle[3].val())) {
elementHandle[3].addClass("error");
errorStatusHandle.text("Please enter your city.");
elementHandle[3].focus();
return false;
}
if(isEmpty(elementHandle[4].val())) {
elementHandle[4].addClass("error");
errorStatusHandle.text("Please enter your state.");
elementHandle[4].focus();
return false;
}
if(!isValidState(elementHandle[4].val())) {
elementHandle[4].addClass("error");
errorStatusHandle.text("The state appears to be invalid, "+
"please use the two letter state abbreviation");
elementHandle[4].focus();
return false;
}
if(isEmpty(elementHandle[5].val())) {
elementHandle[5].addClass("error");
errorStatusHandle.text("Please enter your zip code.");
elementHandle[5].focus();
return false;
}
if(isEmpty(elementHandle[6].val())) {
elementHandle[6].addClass("error");
errorStatusHandle.text("Please enter your cell phone number.");
elementHandle[6].focus();
return false;
}
if(isEmpty(elementHandle[7].val())) {
elementHandle[7].addClass("error");
errorStatusHandle.text("Please enter your email adddress.");
elementHandle[7].focus();
return false;
}
if(isEmpty(elementHandle[8].val())) {
elementHandle[8].addClass("error");
errorStatusHandle.text("Please enter your child's first name.");
elementHandle[8].focus();
return false;
}
if(isEmpty(elementHandle[9].val())) {
elementHandle[9].addClass("error");
errorStatusHandle.text("Please enter your child's last name.");
elementHandle[9].focus();
return false;
}
if(isEmpty(elementHandle[10].val())) {
elementHandle[10].addClass("error");
errorStatusHandle.text("Please enter your child's name that he/she wish to go by.");
elementHandle[10].focus();
return false;
}
if(isEmpty(elementHandle[11].val())) {
elementHandle[11].addClass("error");
errorStatusHandle.text("Please enter your child's date of birth.");
elementHandle[11].focus();
return false;
}
if(isEmpty(elementHandle[12].val())) {
elementHandle[12].addClass("error");
errorStatusHandle.text("Please enter your emergency contact first name.");
elementHandle[12].focus();
return false;
}
if(isEmpty(elementHandle[13].val())) {
elementHandle[13].addClass("error");
errorStatusHandle.text("Please enter your emergency contact last name.");
elementHandle[13].focus();
return false;
}
if(isEmpty(elementHandle[14].val())) {
elementHandle[14].addClass("error");
errorStatusHandle.text("Please enter your emergency contact phone number.");
elementHandle[14].focus();
return false;
}
return true;
}
elementHandle[0].focus();
$(':submit').on('click', function() {
for(var i=0; i < 10; i++)
elementHandle[i].removeClass("error");
errorStatusHandle.text("");
return isValidData();
});
}));

isEmpty function is not defined
isValidState function is not defined
instead of:
$(':submit').on('click', function() {
use:
$('form').submit(function() {

Okay, let's fix this
For starters, you didn't include the isEmpty() function. Therefore, when the code you included was run, your isValidData() function caused an error, which stopped the form from returning false. isValidState() is also undefined, but I'm not going to write that for you
Secondly, I'd suggest instead of using the click event on :submit, use the submit event on form[name=summerForm]. First it narrows your validity checking to just the form you want, and secondly there are more ways to submit a form than just clicking the button. This will catch those.
Thirdly, and most importantly, you didn't include an error message element. The reason you're not seeing anything, is because while you set a .text to .errorMessage, .errorMessage doesn't exist. Refer to this fiddle
http://jsfiddle.net/kaexgob8/
HTML:
<form name="summerForm" method="post" action="signup.html">
<h2>Programs</h2>
<p>Please select the following prgrams:</p>
<select name="programs">
<option value="beginningSpanish">Beginning Spanish</option>
<option value="advancedSpanish">Advanced Spanish</option>
<option value="conversationalSpanish">Conversational Spanish</option>
<option value="advancedConversationalSpanish">Advanced Conversational Spanish</option>
<option value="spanishGrammerAndComposition">Spanish Grammar and Composition</option>
<option value="culturalTreasuresOfMexico">Cultural Treasures of Mexico</option>
</select>
<h2>Parent's Information</h2>
<label for="firstName">First Name:</label>
<input type="text" id="pFirstName" name="pFirstName"/>
<label for="middleName">Middle Name:</label>
<input type="text" id="pMiddleName" name="pMiddleName"/>
<label for="lastName">Last Name:</label>
<input type="text" id="pLastName" name="LastName"/>
<br/>
<strong>Relationship to Child:</strong><br/>
<label for="nameFather">Father</label>
<input type="radio" id="pFather" name="relationship" value="Father"/>
<label for="nameMother">Mother</label>
<input type="radio" id="pMother" name="relationship" value="Mother"/>
<label for="nameGuardian">Guardian</label>
<input type="radio" id="pGuardian" name="relationship" value="Guardian"/>
<br/>
<label for="address1">Address</label>
<input type="text" id="pAddress" name="pAddress"/><br/>
<label for="city1">City</label>
<input type="text" id="pCity" name="pCity"/>
<label for="state1">State</label>
<input type="text" id="pState" size="2" maxlength="2" name="pState"/>
<label for="zipCode1">Zip Code</label>
<input type="text" size="5" maxlength="5" id="pZipCode" name="pZipCode"/><br/>
<label for="homePhone">Home Phone</label>
<input type="text" id="pHomePhone" name="pHomePhone"/>
<label for="cellPhone">Cell Phone</label>
<input type="text" id="pCellPhone" name="pCellPhone"/><br/>
<label for="emailAddress">Email Address:</label>
<input type="text" id="pEmailAddress" name="pEmailAddress"/>
<h2>Child's Information</h2>
<label for="cFirstName">First Name:</label>
<input type="text" id="cFirstName" name="cFirstName"/>
<label for="cMiddleName">Middle Name:</label>
<input type="text" id="cMiddleName" name="cMiddleName"/>
<label for="cLastName">Last Name:</label>
<input type="text" id="cLastName" name="cLastName"/><br/>
<label for="secondName">Name the child goes by:</label>
<input type="text" id="secondName" name="secondName"/><br/>
Photo of child. (recommended format: 400x400 .jpg)<br/>
<input type="file" name="photo"/><br/>
<strong>Gender:</strong><br/>
<label for="cMale">Male</label>
<input type="radio" id="cMale" name="sex" value="Male"/>
<label for="cFemale">Female</label>
<input type="radio" id="cFemale" name="sex" value="Female"/><br/>
<label for="cDOB">Date of Birth:</label>
<input type="date" id="cDOB" size="12" maxlength="10" placeholder="MM/DD/YYYY" name="cDOB"/><br/>
<label for="cMedical">Medical Conditions:</label><br/>
<textarea id="cMedical" name="comments"> </textarea><br/>
<label for="cSDR">Special Dietary Requirements:</label><br/>
<textarea id="cSDR" name="comments"> </textarea><br/>
<p><strong>Secondary Emergency Contact</strong></p>
First Name
<input type="text" name="sFirstName"/>
Last Name
<input type="text" name="sLastName"/>
Phone Number
<input type="text" name="sPhoneNumber"/><br/>
<input type="submit" name="submit" value="Submit"/>
<div class='errorMessage' ></div>
</form>
JS:
var errorStatusHandle = $('.errorMessage');
var elementHandle = new Array (15);
elementHandle[0] = $('[name="pFirstName"]');
elementHandle[1] = $('[name="pLastName"]');
elementHandle[2] = $('[name="pAddress"]');
elementHandle[3] = $('[name="pCity"]');
elementHandle[4] = $('[name="pState"]');
elementHandle[5] = $('[name="pZipCode"]');
elementHandle[6] = $('[name="pCellPhone"]');
elementHandle[7] = $('[name="pEmailAddress"]');
elementHandle[8] = $('[name="cFirstName"]');
elementHandle[9] = $('[name="cLastName"]');
elementHandle[10] = $('[name="secondName"]');
elementHandle[11] = $('[name="cDOB"]');
elementHandle[12] = $('[name="sFirstName"]');
elementHandle[13] = $('[name="sLastName"]');
elementHandle[14] = $('[name="sPhoneNumber"]');
function isEmpty(val)
{
if(val == '' || val === null || val === undefined)
return true;
return false;
}
function isValidData()
{
if(isEmpty(elementHandle[0].val())) {
elementHandle[0].addClass("error");
errorStatusHandle.text("Please enter your first name.");
elementHandle[0].focus();
return false;
}
if(isEmpty(elementHandle[1].val())) {
elementHandle[1].addClass("error");
errorStatusHandle.text("Please enter your last name.");
elementHandle[1].focus();
return false;
}
if(isEmpty(elementHandle[2].val())) {
elementHandle[2].addClass("error");
errorStatusHandle.text("Please enter your address.");
elementHandle[2].focus();
return false;
}
if(isEmpty(elementHandle[3].val())) {
elementHandle[3].addClass("error");
errorStatusHandle.text("Please enter your city.");
elementHandle[3].focus();
return false;
}
if(isEmpty(elementHandle[4].val())) {
elementHandle[4].addClass("error");
errorStatusHandle.text("Please enter your state.");
elementHandle[4].focus();
return false;
}
if(!isValidState(elementHandle[4].val())) {
elementHandle[4].addClass("error");
errorStatusHandle.text("The state appears to be invalid, "+
"please use the two letter state abbreviation");
elementHandle[4].focus();
return false;
}
if(isEmpty(elementHandle[5].val())) {
elementHandle[5].addClass("error");
errorStatusHandle.text("Please enter your zip code.");
elementHandle[5].focus();
return false;
}
if(isEmpty(elementHandle[6].val())) {
elementHandle[6].addClass("error");
errorStatusHandle.text("Please enter your cell phone number.");
elementHandle[6].focus();
return false;
}
if(isEmpty(elementHandle[7].val())) {
elementHandle[7].addClass("error");
errorStatusHandle.text("Please enter your email adddress.");
elementHandle[7].focus();
return false;
}
if(isEmpty(elementHandle[8].val())) {
elementHandle[8].addClass("error");
errorStatusHandle.text("Please enter your child's first name.");
elementHandle[8].focus();
return false;
}
if(isEmpty(elementHandle[9].val())) {
elementHandle[9].addClass("error");
errorStatusHandle.text("Please enter your child's last name.");
elementHandle[9].focus();
return false;
}
if(isEmpty(elementHandle[10].val())) {
elementHandle[10].addClass("error");
errorStatusHandle.text("Please enter your child's name that he/she wish to go by.");
elementHandle[10].focus();
return false;
}
if(isEmpty(elementHandle[11].val())) {
elementHandle[11].addClass("error");
errorStatusHandle.text("Please enter your child's date of birth.");
elementHandle[11].focus();
return false;
}
if(isEmpty(elementHandle[12].val())) {
elementHandle[12].addClass("error");
errorStatusHandle.text("Please enter your emergency contact first name.");
elementHandle[12].focus();
return false;
}
if(isEmpty(elementHandle[13].val())) {
elementHandle[13].addClass("error");
errorStatusHandle.text("Please enter your emergency contact last name.");
elementHandle[13].focus();
return false;
}
if(isEmpty(elementHandle[14].val())) {
elementHandle[14].addClass("error");
errorStatusHandle.text("Please enter your emergency contact phone number.");
elementHandle[14].focus();
return false;
}
return true;
}
$('form [name=summerForm]').on('submit', function()
{
for(var i=0; i < 10; i++)
elementHandle[i].removeClass("error");
errorStatusHandle.text("");
var valid = isValidData();
return valid;
});
.errorMessage {
color: red;
}

Try to use jQuery Validation.
<form name="summerForm" id="summerFormID" method="post" action="signup.html">
<select name="programs">
// options
</select>
<input type="text" id="pFirstName" name="pFirstName"/>
<label for="middleName">Middle Name:</label>
<input type="text" id="pMiddleName" name="pMiddleName"/>
<label for="lastName">Last Name:</label>
<input type="text" id="pLastName" name="LastName"/>
<br/>
. . .
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery/js:
jQuery(document).ready(function(){
$('#summerFormID').validate({
rules: {
programs:{
required: true
},
pFirstName:{
required: true
},
pMiddleName:{
required: true
},
pLastName:{
required: true
}
},
messages: {
programs:{
required: "please select a program!"
},
pFirstName:{
required: "FirstName required!"
},
pMiddleName:{
required: "MiddleName required!"
},
pLastName:{
required: "Last Name Required!"
}
},
submitHandler: function(form){
form.submit();
}
});
});
*You can also try other validation rules or make your own rule. See jQuery Validation page. And don't forget to add the plugin in your program/project.

Related

Disabling a button on empty <select> list?

`I've created a form that allows a user to enter their details and have their first and last names displayed along with a numerical ID. There is a 'Delete' button allowing the user to remove whatever name they select.
by default, the 'Delete' button should be disabled until the <select> list is populated. If all names are deleted from the list - the 'Delete' button should disable again.
That's where im struggling. I cant get the 'Delete' button to enable when a name is added to the list.
Below is my HTML and JavaScript:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.value === 1;
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
console.log("is remove being triggered??")
}
if (Member.options.length == ""){
Delete.disabled = true
}
else {
Delete.disabled = false
}
</script>
</body>
`
The reason why the Delete button is not enabling is because the code that is supposed to enable the Delete button is only run once, when the page loads.
Assuming that this is the code that is supposed to enable the button:
if (Member.options.length == 0){ // changed from Member.options.length == ""
Delete.disabled = true
} else {
Delete.disabled = false
}
This code is only run once, when the page loads and the JavaScript code is run. In order to enable the button properly, we need to run this code every time that Member.options.length changes. One way you can do this is place the code snippet above for disabling/enabling the Delete button inside the onclick listener for the save button and to re-check every time a new user is saved. You would have to add this snippet into every place in your code where Member.options.length could change (inside the listener for the delete button as well).
Full updated code:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.options.length == 0
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
if (Member.options.length == 0){
Delete.disabled = true
}
else {
Delete.disabled = false
}
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
if (Member.options.length == 0) {
Delete.disabled = true
}
else {
Delete.disabled = false
}
console.log("is remove being triggered??")
}
</script>
</body>
so if i understood correctly you want to toggle a button if a is populated
In that case you want to keep track of the options
You can use
document.querySelectoAll('options')
and store it in a variable
then write a function that check if there's a value in that variable and disable or enable the button based on that.
Here's a fiddle:
https://jsfiddle.net/skm7bcr6/15/

Why doesn't Javascript validate my html code?

This is my first attempt at working with javascript and forms; for some reason my html website elements aren't being validated and I am not sure why. My goal with this form is trying to validate the elements that have an '*' next to them. For some reason the only element that is being validated is email and nothing else. Name, dates, the checkbox aren't. I have been trying to find a fix, but nothing seems to work.
<!doctype html>
<html>
<head>
<link href="styles.css" rel="stylesheet">
<script src="script.js"></script>
<meta charset="utf-8">
<title>Form</title>
</head>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span><input type="radio" name="tos" value="yes" checked>I agree</label>
<input type="radio" name="tos" value="yes">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" type="submit" value="Submit">Submit</button>
<button class="btn-reset" type="reset" value="Reset">Reset</button>
</form>
</div>
</body>
</html>
Here is the javascript that is being linked in the html. I am unsure whether the issue is with my html code or with my javascript.
// JavaScript Document
function validateForm()
{
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var dob = document.forms["myForm"]["DOB"].value;
var packages = document.forms["myForm"]["package"].value;
var arrival = document.forms["myForm"]["arrival"].value;
//var interest = document.forms["form"]["interest"].value;
var ToS = document.forms["myForm"]["tos"].value;
var checkbox = document.querySelector('input[name="interest"]:checked');
var matches = name.match(/\d+/g);
if (matches != null) {
alert("Name has a number in it!");
}
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (dob == "") {
alert("Date of Birth must not be empty");
return false;
}
if (arrival == "") {
alert("Arrival Date must not be empty");
return false;
}
if(ToS == false) {
alert("You must agree to the Terms of Service");
return false;
}
if(validateEmail(email) == false){
alert("Must enter a valid email");
}
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(dob != '' && !dob.match(re)) {
alert("Invalid date format");
return false;
}
if(arrival != '' && !arrival.match(re)) {
alert("Invalid arrival date format") ;
return false;
}
if(name.length >= 30){
alert("Name must be less than 30 characters!");
return false;
}
if(!checkbox){
alert("Please select an interest!");
return false;
}
}
function validateEmail(email)
{
return /\S+#\S+\.\S+/.test(email);
}
So I have no idea what your PHP form did, so I actually just pulled all the form code for now. There were a lot of little issues but honest mistakes. Example: you don't want a return statement after every validation if you want to continue validating the rest of the fields. I combined some separate validations into if/else's since they were validations on the same field. I used ID's to make my life easier and since I dumped the form code. Feel free to swap back to what you want. I also updated your regex since the date field returns YYYY/MM/DD. Since this doesn't post anywhere you can play with it for a while, before tying back into your php form. I also pulled the check for 30 characters and added a max field length to name. You could also set min and max date ranges for the date fields and a bunch of other things to help make the fields themselves more foolproof. There are also libraries that handle this kind of thing for you, you don't have to re-invent the wheel, but if you're just looking to play around with it this should get you started. Good Luck
<!doctype html>
<html>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" id='name' maxlength="30" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input id="email" type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" id="dob" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select id='package' name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" id="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span>
<input type="radio" name="tos" id="accpeted" value="agree" checked>I agree</label>
<input type="radio" name="tos" id="unaccepted" value="disagree">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" id="submit" onclick="return validateForm()">Submit</button>
</div>
<script>
// JavaScript Document
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var dob = document.getElementById("dob").value;
//Select Box
var e = document.getElementById("package");
// Selected Item
var packages = e.options[e.selectedIndex].value;
var arrival = document.getElementById("arrival").value;
//var interest = document.getElementById("").value;
var tos = document.querySelector('input[name="tos"]:checked').value;
//var checkbox = document.getElementById("").value;;
var matches = name.match(/\d+/g);
var re = /^\d{4}([.\/-])\d{2}\1\d{2}$/;
if (!name) {
alert("Name must be filled out");
} else {
if (matches != null) {
alert("Name has a number in it!: " + name);
}
}
if (!email) {
alert("Email must be filled out");
} else {
if (validateEmail(email) == false) {
alert("Must enter a valid email: " + email);
}
}
if (!dob) {
alert("Date of Birth must not be empty");
} else {
if (!dob.match(re)) {
alert(" Dob has Invalid date format: " + dob);
}
}
if (!arrival) {
alert("Arrival Date must not be empty");
} else {
if (!arrival.match(re)) {
alert(" Dob has Invalid date format: " + arrival);
}
}
if (tos != "agree") {
alert("You must agree to the Terms of Service");
}
}
function validateEmail(email) {
return /\S+#\S+\.\S+/.test(email);
}
</script>
</body>
</html>

My Jquery does not connect to my html

my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});

Radio Button Validation Error

For the gender radio button validation within the validate function below, the alert occurs whenever neither of the gender radio buttons are selected. However, whenever "ok" is selected within the browser, the form is submitted. What seems to be causing that problem? Also I would like for it to be focused like the rest when returned false, if that is possible.
JavaScript
function validate()
{
var gender = document.getElementsByName("gender");
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
document.myForm.firstname.focus() ;
return false;
}
if( document.myForm.lastname.value == "" )
{
alert( "Please provide your last name!" );
document.myForm.lastname.focus() ;
return false;
}
if( document.myForm.email.value == "" )
{
alert( "Please provide your email!" );
document.myForm.email.focus() ;
return false;
}
if( (gender[0].checked == false) && (gender[1].checked == false))
{
alert( "Please provide your gender!" );
document.myForm.male.focus() ;
return false;
}
if( document.myForm.date.value == "" )
{
alert( "Please provide a date to be performed!" );
document.myForm.date.focus() ;
return false;
}
if( document.myForm.vname.value == "" )
{
alert( "Please provide a victim's name!" );
document.myForm.vname.focus() ;
return false;
}
if( document.myForm.vemail.value == "" )
{
alert( "Please provide the victim's email!" );
document.myForm.vemail.focus() ;
return false;
}
return( true );
}
HTML:
<div id="box">
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" placeholder="user#mydomain.com" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" placeholder="Mary Jane" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" placeholder="user#mydomain.com" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" value="Submit"/> <br>
</form>
</div>
I've figured out the solution. Instead of having:
if( (gender[0].checked == false) && (gender[1].checked == false))
{
alert( "Please provide your gender!" );
document.myForm.male.focus() ;
return false;
}
It should be:
if( (gender[0].checked == false) && (gender[1].checked == false))
{
alert( "Please provide your gender!" );
document.myForm.male.focus() ;
return true;
}
I did this & the validation is working perfectly.
Just provide a default for gender.
<input type="radio" name="gender" id="gender" value="male" checked/>
This will avoid any possible confusion and requires less validation overall.
You are defining your validate() function but I don't see you actually calling it when you submit the document. A submit input on it's own does not know about your validation.
Maybe change:
<input type="submit" value="Submit"/>
to
<input type="button" value="Submit" onClick="if(validate==true) {document.forms[0].submit()}" />
I would select according to different IDs naming them male and female and and call the validate function as ElPedro suggests.
I think it was issue with the focus function.
I made few changes and it worked.
<div id="box">
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return validate();">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" placeholder="user#mydomain.com" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" placeholder="Mary Jane" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" placeholder="user#mydomain.com" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" value="Submit"/> <br>
</form>
</div>
<script>
function validate(e)
{
var gender = document.getElementsByName("gender");
if( document.myForm.firstname.value == "" )
{
alert( "Please provide your first name!" );
return false;
}
if( document.myForm.lastname.value == "" )
{
alert( "Please provide your last name!" );
return false;
}
if( document.myForm.email.value == "" )
{
alert( "Please provide your email!" );
return false;
}
if( (gender[0].checked == false) && (gender[1].checked == false))
{
alert( "Please provide your gender!" );
return false;
}
if( document.myForm.date.value == "" )
{
alert( "Please provide a date to be performed!" );
return false;
}
if( document.myForm.vname.value == "" )
{
alert( "Please provide a victim's name!" );
return false;
}
if( document.myForm.vemail.value == "" )
{
alert( "Please provide the victim's email!" );
return false;
}
return true;
}
</script>
dont know if is the right answer but i uses that way and after evething i pass the variable value as my defined wish and passes to the form :)
var swticher = document.getElementById('swticher-on');
var swticher_off = document.getElementById('swticher-off');
function check(e){
if(e.checked == swticher.checked)
{
// you can set the value for on as default by set valirable in it
var val = swticher.value = "1";
alert('on -> '+val);
}
else if(e.checked == swticher_off.checked)
{
// you can set the value for off as default by set valirable in it
var val = swticher.value = "0";
alert('off -> '+val);
}
}
<!-- i dont know this is the right answer but i use this way somethings -->
<div class="col-sm-2">
<input type="radio" id="swticher-on" name="swticher" value="1" class="form-control swticher-in" onclick="check(this)">
<label for="swticher-on">ON</label>
</div>
<div class="col-sm-2">
<input type="radio" id="swticher-off" name="swticher" value="0" class="form-control swticher-in" checked onclick="check(this)">
<label for="swticher-off"><b class="text-danger">OFF</b></label>
</div>

trouble validating various inputs with jQuery

for a class project I have to build a website for a pet store, featuring a pet grooming service. This involves a form, php and a mysql server on my localhost. I have been unable to correctly validate this form via a jQuery validator plugin for some unknown (to me) reason.
I've had no luck via regular jQuery code beyond getting the form to not submit blank input values. So as it is, anybody can put 'sadklfhsdk' in any of the fields (except for email, unless it has a '#') and it will validate and submit to the server.
So after I going through a couple of tutorials this is what I have so far:
The HTML:
<body>
<div id="h2Groom"><h2>Grooming Request Form</h2></div>
<form id="groom_form" method="post" action="insertPS.php">
<div id="result"></div>
<label for="firstName"><span>First Name:</span>
<input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name" class="required"/>
</label>
<label for="lastName"><span>Last Name:</span>
<input type="text" name="lastName" id="lastName" placeholder="Enter Your Last Name" class="required"/>
</label>
<label for="email"><span>Email Address:</span>
<span id="error"></span>
<input type="email" name="email" id="email" placeholder="Enter a Email"/>
</label>
<label for="phone"><span>Phone Number:</span>
<span id="error"></span>
<input type="text" name="phone" id="phone" placeholder="Enter a phone number" class="required"/>
</label>
<label for="address"><span>Address:</span>
<input type="text" name="address" id="address" placeholder="Enter your address" class="required"/>
</label>
<label for="city"><span>City:</span>
<input type="text" name="city" id="city" placeholder="Enter your city" />
</label>
<label for="state"><span>State:</span>
<input type="text" name="state" id="state" placeholder="Enter your state" class="required"/>
</label>
<label for="zipcode"><span>Zipcode:</span>
<input type="text" name="zipcode" id="zipcode" placeholder="Enter your zipcode" class="required"/>
</label>
<label for="petType"><span>Type of Pet:</span>
<ul>
<li><label><input name="petType" type="radio" value="dog" id="dog">Dog</label></li>
<li><label><input name="petType" type="radio" value="cat" id="cat">Cat</label></li>
<li><label><input name="petType" type="radio" value="bird" id="bird">Bird</label></li>
</ul>
</label>
<select id="breed" name="breed">
<option value="0">--Please Choose Dog Breed--</option>
<option value="AlaskanMal">Alaskan Malamute</option>
<option value="Bichon">Bichon Frise</option>
<option value="WelshCorgi">Corgi, Welsh</option>
<option value="Dalmation">Dalmation</option>
<option value="EnglishToySpan">English Toy Spaniel</option>
<option value="FrenchBull">French Bull Dog</option>
<option value="Greyhound">Greyhound</option>
<option value="Papillon">Papillon</option>
<option value="Rottweiler">Rottweiler</option>
<option value="YorkshireTerr">Yorkshire Terrier</option>
</select>
<label for="neut"><span>Check box if your pet has been neutered/spayed (leave unchecked if not).</span></label>
<ul>
<label>
<li><input type="checkbox" name="neut" id="neut" />Yes</li></label>
</ul>
<br />
<br />
<br />
<label for="petname"><span>Pet Name:</span>
<input type="text" name="petname" id="petname" placeholder="Enter your pet's name" class="required" />
</label>
<label for="petBday"><span>Pet's Birthday:</span>
<input type="date" id="petBday" name="petBday"/>
</label>
<span> </span>
<input type="submit" id="submitBttn" value="Submit" /><input type="reset" id="resetBttn" value="Reset" />
</form>
</body>
The jQUERY (except the script to send values to server, see jsfiddle link):
$(document).ready(function() {
$('input[name=petType]').click(function() {
if(this.id=='dog') {
$('#breed').show('slow');
}
else {
$('#breed').hide('slow');
}
});
$('input[name=phone]').blur(function() {
if (validatePhone('phone')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$('input[name=email]').blur(function() {
if (validateEmail('email')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$("#submitBttn").click(function() {
//get input field values
var user_firstName = $('input[name=firstName]').val();
var user_lastName = $('input[name=lastName]').val();
var user_email = $('input[name=email]').val();
var user_address = $('input[name=address]').val();
var user_phone = $('input[name=phone]').val();
var user_city = $('input[name=city]').val();
var user_state = $('input[name=state]').val();
var user_zipcode = $('input[name=zipcode]').val();
var user_petname = $('input[name=petname]').val();
var checked_radio = $('input:radio[name=petType]').is(':checked');
var user_neut = $('input:checkbox[name=neut]').is(':checked');
var user_breed = $('input:select[name=breed]').is(':selected');
var txtVal = $('#petBday').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
var proceed = true;
//Validation functions, executed when user hits "submit"
function validatePhone(phone) {
var a = document.getElementById(phone).value;
var filter = /^[0-9-+]+$/;
if (filter.text(phone)) {
return true;
}
else {
return false;
}
}
function validateEmail(email) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
return true;
}
else {
return false;
}
}
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
//declare regex
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern); //is the format ok?
if(dtArray ==null)
return false;
//checks for mm/dd/yyyy format
dtMonth = dtArray[1];
dtDay = dtArray[3];
dtYear = dtArray[5];
if(dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay > 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if(dtDay > 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
EDIT: corrected if(filter.text()) to if(filter.test(phone)). None of my java validation code works.
validatePhone: filter.text should be spelled test

Categories

Resources