Every time I submit the form even when the form is empty it take me to my controller.
It doesn't validate the html form with required and it doesn't respond on javascript validation onsubmit. I have tried on the submit button onclick still the same problem.
The confusing part is that the input required not even working either required="required" or required.
The only validation that is working is the type="email" and type="number" the rest nothing.
I check my js file it works fine.
Thank you
/*----------------------VALIDATION INPUT REGISTRATION FORM---------------------*/
function validate_register_form() {
var first_name = document.forms["register_form"]["first_name"].value;
var last_name = document.forms["register_form"]["last_name"].value;
var email = document.forms["register_form"]["email"].value;
var password = document.forms["register_form"]["password"].value;
var retype_password = document.forms["register_form"]["retype_password"].value;
var mobile_number = document.forms["register_form"]["mobile_number"].value;
var gender = document.forms["register_form"]["gender"].value;
var p_b = document.forms["register_form"]["p_b"].value;
var privacy = document.forms["register_form"]["one"].value;
if(first_name == null || first_name == "") {
document.getElementById('first_name').style.borderColor = "red";
alert("First Name must be filled out");
return false;
}else{
document.getElementById('first_name').style.borderColor = "green";
}
if(last_name == null || last_name == "") {
document.getElementById('last_name').style.borderColor = "red";
alert("Last Name must be filled out");
return false;
}else{
document.getElementById('last_name').style.borderColor = "green";
}
if(email == null || email == ""){
document.getElementById('email').style.borderColor = "red";
alert("Email must be filled out");
return false;
}else{
document.getElementById('email').style.borderColor = "green";
}
if(password == null || password == ""){
document.getElementById('password').style.borderColor = "red";
alert("Password must be filled out");
return false;
}else{
document.getElementById('password').style.borderColor = "green";
}
if(retype_password == null || retype_password == ""){
document.getElementById('retype_password').style.borderColor = "red";
alert("retype password must be filled out");
return false;
}else{
document.getElementById('retype_password').style.borderColor = "green";
}
if(password != retype_password){
document.getElementById('password').style.borderColor = "red";
document.getElementById('retype_password').style.borderColor = "red";
alert("password not match");
return false;
}else{
document.getElementById('password').style.borderColor = "green";
document.getElementById('retype_password').style.borderColor = "green";
}
if(mobile_number == null || mobile_number == ""){
document.getElementById('mobile_number').style.borderColor = "red";
alert("Mobile number must be filled out");
return false;
}else{
document.getElementById('mobile_number').style.borderColor = "green";
}
if(gender == null || gender == ""){
document.getElementById('gender').style.borderColor = "red";
alert("Gender must me filled out");
return false;
}else{
document.getElementById('gender').style.borderColor = "green";
}
if(p_b == null || p_b == ""){
document.getElementById('p_b').style.borderColor = "red";
alert("Persoanl or Dealer must be filled out");
return false;
}else{
document.getElementById('p_b').style.borderColor = "green";
}
if(privacy == null || privacy == "" || privacy != "on"){
document.getElementById('privacy').style.borderColor = "red";
alert("Privacy must be checked in order to submit the form");
return false;
}else{
document.getElementById('privacy').style.borderColor = "green";
}
return true;
} // end of registration validation form registration.php
<form action="controllers/core.php" method="post" onsubmit="return validate_register_form(this);">
<div class="gray-form" id="register_form">
<div class="row">
<div class="form-group col-md-6">
<label>Your Name*</label>
<input class="form-control" type="text" placeholder="Your Name" name="first_name" id="first_name" required />
</div>
<div class="form-group col-md-6">
<label>Last Name*</label>
<input class="form-control" type="text" placeholder="Last Name" name="last_name" id="last_name" required />
</div>
</div>
<div class="form-group">
<label>Email *</label>
<input class="form-control" type="email" placeholder="Enter your email" name="email" id="email" required />
</div>
<div class="form-group">
<label>Password* </label>
<input class="form-control" type="password" placeholder="Password" name="password" id="password" required />
</div>
<div class="form-group">
<label>Re-enter Password*</label>
<input class="form-control" type="password" placeholder="Password" name="retype_password" id="retype_password" required />
</div>
<div class="form-group">
<label>Mobile phone *</label>
<input class="form-control" type="number" placeholder="Enter your mobile no" id="mobile_number" name="mobile_number" required />
</div>
<div class="form-group">
<label>Gender *</label>
<div class="selected-box">
<select name="gender" id="gender" class="form-control">
<option value="">I am</option>
<option value="male">male</option>
<option value="female">Female</option>
<option value="Business">Business</option>
</select>
</div>
</div>
<div class="form-group">
<label>Personal or Dealer *</label>
<div class="selected-box">
<select name="p_b" id="p_b" class="form-control">
<option value="">I am looking for a </option>
<option value="personal">Personal Account</option>
<option value="dealer">Dealer Account</option>
</select>
</div>
</div>
<div class="form-group">
<div class="remember-checkbox">
<input type="checkbox" name="privacy" id="one" />
<label for="one">Accept our privacy policy and customer agreement</label>
</div>
</div>
<button type="submit" class="button red" name="register"> Register an account </button>
<p class="link">Already have an account? please login here </p>
</div>
</form>
Added a name attribute to the form, and remove required from every field, required will be the basic HTML validation so no need of that in your custom validation method.
<form action="controllers/core.php" method="post" onsubmit="return validate_register_form(this);" name='register_form'>
/*----------------------VALIDATION INPUT REGISTRATION FORM---------------------*/
function validate_register_form() {
var first_name = document.forms["register_form"]["first_name"].value;
var last_name = document.forms["register_form"]["last_name"].value;
var email = document.forms["register_form"]["email"].value;
var password = document.forms["register_form"]["password"].value;
var retype_password = document.forms["register_form"]["retype_password"].value;
var mobile_number = document.forms["register_form"]["mobile_number"].value;
var gender = document.forms["register_form"]["gender"].value;
var p_b = document.forms["register_form"]["p_b"].value;
var privacy = document.forms["register_form"]["one"].value;
if(first_name == null || first_name == "") {
document.getElementById('first_name').style.borderColor = "red";
alert("First Name must be filled out");
return false;
}else{
document.getElementById('first_name').style.borderColor = "green";
}
if(last_name == null || last_name == "") {
document.getElementById('last_name').style.borderColor = "red";
alert("Last Name must be filled out");
return false;
}else{
document.getElementById('last_name').style.borderColor = "green";
}
if(email == null || email == ""){
document.getElementById('email').style.borderColor = "red";
alert("Email must be filled out");
return false;
}else{
document.getElementById('email').style.borderColor = "green";
}
if(password == null || password == ""){
document.getElementById('password').style.borderColor = "red";
alert("Password must be filled out");
return false;
}else{
document.getElementById('password').style.borderColor = "green";
}
if(retype_password == null || retype_password == ""){
document.getElementById('retype_password').style.borderColor = "red";
alert("retype password must be filled out");
return false;
}else{
document.getElementById('retype_password').style.borderColor = "green";
}
if(password != retype_password){
document.getElementById('password').style.borderColor = "red";
document.getElementById('retype_password').style.borderColor = "red";
alert("password not match");
return false;
}else{
document.getElementById('password').style.borderColor = "green";
document.getElementById('retype_password').style.borderColor = "green";
}
if(mobile_number == null || mobile_number == ""){
document.getElementById('mobile_number').style.borderColor = "red";
alert("Mobile number must be filled out");
return false;
}else{
document.getElementById('mobile_number').style.borderColor = "green";
}
if(gender == null || gender == ""){
document.getElementById('gender').style.borderColor = "red";
alert("Gender must me filled out");
return false;
}else{
document.getElementById('gender').style.borderColor = "green";
}
if(p_b == null || p_b == ""){
document.getElementById('p_b').style.borderColor = "red";
alert("Persoanl or Dealer must be filled out");
return false;
}else{
document.getElementById('p_b').style.borderColor = "green";
}
if(privacy == null || privacy == "" || privacy != "on"){
document.getElementById('privacy').style.borderColor = "red";
alert("Privacy must be checked in order to submit the form");
return false;
}else{
document.getElementById('privacy').style.borderColor = "green";
}
return true;
} // end of registration validation form registration.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="controllers/core.php" method="post" onsubmit="return validate_register_form(this);" name='register_form'>
<div class="gray-form" id="register_form">
<div class="row">
<div class="form-group col-md-6">
<label>Your Name*</label>
<input class="form-control" type="text" placeholder="Your Name" name="first_name" id="first_name" />
</div>
<div class="form-group col-md-6">
<label>Last Name*</label>
<input class="form-control" type="text" placeholder="Last Name" name="last_name" id="last_name" />
</div>
</div>
<div class="form-group">
<label>Email *</label>
<input class="form-control" type="email" placeholder="Enter your email" name="email" id="email" />
</div>
<div class="form-group">
<label>Password* </label>
<input class="form-control" type="password" placeholder="Password" name="password" id="password" />
</div>
<div class="form-group">
<label>Re-enter Password*</label>
<input class="form-control" type="password" placeholder="Password" name="retype_password" id="retype_password" />
</div>
<div class="form-group">
<label>Mobile phone *</label>
<input class="form-control" type="number" placeholder="Enter your mobile no" id="mobile_number" name="mobile_number" />
</div>
<div class="form-group">
<label>Gender *</label>
<div class="selected-box">
<select name="gender" id="gender" class="form-control">
<option value="">I am</option>
<option value="male">male</option>
<option value="female">Female</option>
<option value="Business">Business</option>
</select>
</div>
</div>
<div class="form-group">
<label>Personal or Dealer *</label>
<div class="selected-box">
<select name="p_b" id="p_b" class="form-control">
<option value="">I am looking for a </option>
<option value="personal">Personal Account</option>
<option value="dealer">Dealer Account</option>
</select>
</div>
</div>
<div class="form-group">
<div class="remember-checkbox">
<input type="checkbox" name="privacy" id="one" />
<label for="one">Accept our privacy policy and customer agreement</label>
</div>
</div>
<button type="submit" class="button red" name="register"> Register an account </button>
<p class="link">Already have an account? please login here </p>
</div>
</form>
Related
`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/
Okay, I'm trying to get a contact form to work and it is, sort of. The data is passing through, but I can't get the jQuery to work. If I type in two different email addresses it doesn't catch it. Here is the relevant code I used:
HTML
<aside>
<form action="sendmail.php" method="post" name="contact_form" id="contact_form">
<fieldset>
<legend>sign up now!</legend><br>
<p>Sign up for my email list and get a free mini coloring book!</p><br>
<img src="Images/minicoloirngbook.jpg" alt="mini coloring book"><br>
<label for="name"> Name:</label>
<input type="text"name="name" id="name" required><span>*</span><br>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" required><span>*</span><br>
<label for="verify">Verify Email:</label>
<input type="email" name="verify" id="verify" required> <span>*</span><br>
<div id="buttons">
<input type="submit" id="submit" value="Sign Up">
</div>
</fieldset>
</form>
</aside>
and here is the Javascript:
$("#contact_form").submit(event => {
let isValid = true;
// validate the first name entry
const name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
} else {
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
I think that the answer is probably something really simple that I can't see and would appreciate your help in figuring it out.
This should do it. Here is the jsfiddle if you like to play with the code: https://jsfiddle.net/bogatyr77/xk6ez3aq/7/
$("form").submit(function(e) {
var name = $("#a").val();
if (name == "") {
$("#nameerror").text("This field is required.");
alert('false');
} else {
alert('true');
$("#nameerror").remove();
}
//email1
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#b").val();
if (email == "") {
$("#email1error").text("This field is required.");
isValid = false;
} else if (!emailPattern.test(email)) {
$("#email1error").text("Must be a valid email address.");
isValid = false;
} else {
$("#email1error").remove();
}
//eamil 2
var verify = $("#c").val();
if (verify == "") {
$("#email2error").text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#email2error").text("Must match first email entry.");
isValid = false;
} else {
$("#email2error").remove();
}
if (isValid == false) {
event.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="javascript:alert('ok')">
<label for="name"> Name:</label>
<input type="text" name="name" id="a"><span>*</span>
<div id="nameerror"></div><br>
<label for="email">Email Address:</label>
<input type="text" name="email" id="b"><span>*</span>
<div id="email1error"></div><br>
<label for="verify">Verify Email:</label>
<input type="text" name="verify" id="c"> <span>*</span>
<div id="email2error"></div><br>
<input type="submit" value="submit" />
</form>
<div></div>
This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>
on my local server it works just fine but as soon as I take it live it starts only refershing the page instead of calling the validation.
This is my jquery:
<script>
$("form#registerform").submit(
function (e) {
e.preventDefault();
function validateForm() {
var RegisterUsername = document.forms["contactForm"]["RegisterUsername"].value;
var FirstName = document.forms["contactForm"]["FirstName"].value;
var LastName = document.forms["contactForm"]["LastName"].value;
var Email = document.forms["contactForm"]["Email"].value;
var RegisterPassword = document.forms["contactForm"]["RegisterPassword"].value;
if (RegisterUsername == null || RegisterUsername == "") {
$(".error-messages").text("Username required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (FirstName == null || FirstName == "") {
$(".error-messages").text("First name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
} else if (LastName == null || LastName == "") {
$(".error-messages").text("Last name required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (Email == null || Email == "") {
$(".error-messages").text("Email required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
else if (RegisterPassword == null || RegisterPassword == "") {
$(".error-messages").text("Password required").fadeIn(300).delay(1000).fadeOut(300);
return false;
}
}
}
</script>
This is my html:
<form id="registerform" name="contactForm" action="" onsubmit="return validateForm()" method="post">
<div class="pl-land-input">
<input class="email text-input" id="RegisterUsername" pattern=".{3,}" title="3 characters minimum" name="RegisterUsername" placeholder="Username" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="FirstName" name="FirstName" placeholder="First Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" id="LastName" name="LastName" placeholder="Last Name" type="text" value="">
</div>
<div class="pl-land-input">
<input class="email text-input" type="email" placeholder="Email" name="Email" id="Email">
</div>
<div class="pl-land-input">
<input class="email text-input" id="RegisterPassword" name="RegisterPassword" placeholder="Password" type="password">
</div>
<button type="submit" value="Submit" class="signup-plland">Sign up</button>
</form>
I have been trying to get my head around it and kept customizing it but I couldn't figure out the problem there was no problem in console for calling the Jquery libs.
I hope I can solve this asap.
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