I have a form for allowing the user to change their account password, like so:
<div class="signup-form-small">
<form method="post" name="frmPassword" id="frmPassword" class="needs-validation" novalidate>
<div class="form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="curpwd" name="curpwd" required>
<label class="form-label" for="curpwd">Your Current Password</label>
</div>
</div>
<div class="form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="newpwd" name="newpwd" required>
<label class="form-label" for="newpwd">Enter New Password</label>
</div>
</div>
<div class="row form-group">
<div class="col form-floating">
<input type="password" class="form-control" id="cnfpwd" name="cnfpwd" required>
<label class="form-label" for="cnfpwd">Confirm New Password</label>
</div>
</div>
<div class="form-group">
<button type="submit" id="btnPwdSubmit" name="btnPwdSubmit" class="btn btn-primary btn-lg btn-block w-100 has-spinner">
<div class="spinner-border float-right hidden" id="pwdspinner" role="status"></div>
Change My Password
</button>
</div>
</form>
</div>
In my script I have the following code block which should universally handle validation:
$(document).ready(function () {
'use strict';
window.addEventListener('load', function () {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
});
and finally, here is the script code that fires when the user clicks the 'Chnage My Password' button in the form:
$('#frmPassword').submit(function (event) {
event.preventDefault();
setPwdDisabled();
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1) {
obj.Is_Body_HTML = true;
}
else {
obj.Is_Body_HTML = false;
}
if (obj.Is_Active == 1) {
obj.Is_Active = true;
}
else {
obj.Is_Active = false;
}
if ($('#curpwd').val() != $('#cnfpwd').val()) {
$('toastPwd').toast('show)');
return;
}
var json = JSON.stringify(obj);
var request = $.ajax({
url: "../handlers/changepwd.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#spnPwdErr').html(msg.Status);
$('#toastPwdFail').toast('show');
}
else
$('#toastPwdSuccess').toast('show');
});
request.fail(function (jqXHR, textStatus) {
$('#spnPwdErr').html('Unable to complete your request at this time.');
$('#toastPwdFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setPwdEnabled();
});
});
For whatever reason, the form validation never fires, and I don't know why. I added alerts into the validation code and they never pop up. The form submission happens no matter what. I don't get any errors or other messages in the console. Can anyone shed any light on why this is not functioning?
Remove the add event listener - having it inside the jquery ready makes it redundant -
$(document).ready(function () {
'use strict';
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
});
Related
I can't get my form to validate despite having the script both on the page and in my boilerplate layout. I have tried moving the tags around to different places but the server-side validation is the only part working.. the form won't run the client side validation.
<% layout('layouts/boilerplate') %>
<div class="row">
<h1 class="text-center">Create Artist Profile</h1>
<div class="col-6 offset-3">
<form action="/artists/new" method="POST" novalidate class="validated-form" enctype="multipart/form-data">
<div class="mb-3">
<label class="form-label" for="email">Email</label>
<input class="form-control" type="email" id="email" name="email" placeholder="name#domain.com" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label for="formFile" class="form-label">Upload band photo</label>
<input class="form-control" type="file" id="image" name="image" multiple="false">
</div>
<div class="mb-3">
<button class="btn btn-success">Create Profile</button>
</div>
All artists
</form>
</div>
</div>
Here's the script tag from the body of my layouts/boilerplate.ejs
<script>
(function () {
'use strict'
bsCustomFileInput.init()
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.validated-form')
// Loop over them and prevent submission
Array.from(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})
</script>
Any ideas what I'm doing wrong with this form?
have you tried changing the form class to "needs-validation"?
also try this code
(function() {
'use strict';
window.addEventListener('load', function() {
var forms = document.querySelectorAll('.validated-form')
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
I have a simple form with Ajax call, but ajax call gets executed even if form is not validated.
In below code line console.log("This line should execute only if Form is validated"); gets executed when form is not validate.
Bootstrap 5 validation Codepen code
(function () {
"use strict";
const forms = document.querySelectorAll(".requires-validation");
Array.from(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
else
{
console.log("This line should execute only if Form is validated");
// Call Ajax Function
// AjaxCallSaveData();
}
form.classList.add("was-validated");
},
false
);
});
})();
//$(document).ready(function () {
function AjaxCallSaveData()
{
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#message").val(),
superheroAlias: $("#superheroAlias").val()
};
$.ajax({
type: "POST",
url: "SubmitFORM.php",
data: formData,
dataType: "json",
encode: true
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
}
//});
Not sure if i am doing it right?
HTML
<div class="form-body">
<div class="row">
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<h3>Register you interest</h3>
<p>Fill in the data below, we will get back to you!</p>
<form class="requires-validation" action="SubmitFORM.php" method="POST" novalidate>
<div class="col-md-12 mb-3">
<input class="form-control" type="text" name="name" id="name" placeholder="Full Name" required>
<div class="valid-feedback">Username field is valid!</div>
<div class="invalid-feedback">Username field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<input class="form-control" type="email" name="email" id="email" placeholder="E-mail Address" required>
<div class="valid-feedback">Email field is valid!</div>
<div class="invalid-feedback">Email field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<textarea name="message" id="message" placeholder="Your Message"></textarea>
</div>
<div class="form-button mt-3">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
event.preventDefault() will only stop the form from submitting. It cannot stop next lines of the JavaScript function from executing.
You should use return in place of event.preventDefault().
I am using the bootstrap 'needs-validation' for checking the validation form. Here when I click the submit button its validating the field and form is also getting submitted. What I want is when the validation fails the form should not get submitted. I found the form validation from (needs validation) from here https://www.w3schools.com/bootstrap4/bootstrap_forms.asp and I used it in my program.
My script is
<div class="row top-space-30">
<form class="needs-validation" novalidate action="" method="">
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="studentname">Student Name:</label>
<div class="col-md-6">
<input id="role" name="studentname" type="text" placeholder="name" class="form-control input-md"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="department">Department:</label>
<div class="col-md-8">
<input class="form-control" type="text" id="department">
<input type="hidden" id="TestHidden" value="{{result}}" required>
</div>
</div>
<div class="col-md-6 offset-md-4 top-space-30">
<button type="submit" id="submit">Submit</button>
</div>
</form>
</div>
</div>
<script>
// Disable form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
$("#submit").click(function (e) {
var studentName = $("#role").val();
var departmentsList = $("#department").val().split(',');
$.ajax({
type: 'POST',
url: '/students/add',
data: {
'role': studentName,
'departmentslist': JSON.stringify(departmentsList)
},
success: function (result) {
alert("The department has been added");
document.location.href = "/department";
}
})
})
</script>
Try this one, I have one function for validationsformSubmit add your own validations in that function.
<div class="row top-space-30">
<form class="needs-validation" name="myForm" action="" method="" onsubmit=" return formSubmit()" >
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="studentname">Student Name:</label>
<div class="col-md-6">
<input id="role" name="studentname" type="text" placeholder="name" class="form-control input-md"
required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label text-md-right" for="department">Department:</label>
<div class="col-md-8">
<input class="form-control" type="text" name = "departmentname" id="department">
<input type="hidden" id="TestHidden" value="{{result}}" required>
</div>
</div>
<div class="col-md-6 offset-md-4 top-space-30">
<button type="Submit" id="submit">Submit</button>
</div>
</form>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script>
//Disable form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Get the forms we want to add validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
function formSubmit(){
var forms = document.forms["myForm"];
var studenName = forms.studentname.value;
var departmentName = forms.departmentname.value;
// perform validation for studentname and departname if they are validated then return true, else for wrong input return false
if(isNaN(studentname) && isNaN(departmentname)){
return true;
}
else{
return false;
}
}
$("#submit").click(function (e) {
var studentName = $("#role").val();
var departmentsList = $("#department").val().split(',');
$.ajax({
type: 'POST',
url: '/students/add',
data: {
'role': studentName,
'departmentslist': JSON.stringify(departmentsList)
},
success: function (result) {
alert("The department has been added");
document.location.href = "/department";
}
})
})
</script>
I am trying to reach my javascript code when I press the submit button within my form and it is not triggering my javascript code at all.
So I got this form within my Bootstrap Modal using the following code:
<form id="updateUserForm">
<div class="form-group">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstnameModalInput" />
</div>
<div class="form-group">
<label for="middleName">Middle name:</label>
<input type="text" class="form-control" id="middlenameModalInput" />
</div>
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastnameModalInput" />
</div>
<div class="form-group">
<label for="mobileNumber">Mobile number:</label>
<input type="text" class="form-control" id="mobilenumberModalInput" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="emailModalInput" />
</div>
<div class="form-group">
<label for="Enabled">Enabled:</label>
<input type="checkbox" class="form-control" id="enabledModalInput" style="width:34px" />
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" data-dismiss="modal" id="submit" value="Apply" />
</div>
</form>
And the javascript code I have:
$('document').ready(function(){
$("#updateUserForm").submit(function (event) {
console.log("Method entered");
event.preventDefault();
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
})
})
I have another function in that javascript that is used to populate the input fields and that works fine, so I guess the HTML can reach the javascript file. But it does not reach the javascript submit function (it doesn't do the console.log for example) . Does anyone have an idea what I am doing wrong?
EDIT:
I have been playing around a bit more, and it seems that I can acces the javascript method when I try to reach it from outside of the bootstrap modal, it goes wrong somewhere within the modal.
Use return false instead of prevent default end of the function and change the submit function with on function.
$('document').ready(function(){
$("#updateUserForm").on("submit", function () {
console.log("Method entered");
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
return false;
})
})
try this
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Can you please try below code. and please check post URL"/Dashboard/UpdateUser" is right?
$("#UpdateUserForm").submit(function (e)
{
var isValid = $("#UpdateUserForm").valid();
if (!isValid)
return;
//This is important as it prevents the form being submitted twice
e.preventDefault();
$.ajax({
type: "POST",
url: "/Dashboard/UpdateUser",
data: $("#UpdateUserForm").serialize(),
success: function (response)
{
var status = '';
status = response.Status;
console.log("succes!");
console.log(data);
}
})
.error(function () {
console.log("error");
console.log(data);
});
});
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Or use action properties in form.
My form submission does not work . Nothing happens when i submit the form. I tried everything but no result.
I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code.
My code
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('contact_queryf').bind('click', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'Views/query_send.php',
data: $('contact_queryf').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
my form code
<form role="form" method="post" id="contact_queryf" name="contact_queryf">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email" required>
</div>
<div class="form-group">
<div class="radio-inline">
<label class="radio-inline">
<input type="radio" name="qtype" id="qtype" value="Android" required>Android
</label>
<label class="radio-inline">
<input type="radio" name="qtype" id="qtype" value="iOS" required>iOS
</label>
<label class="radio-inline">
<input type="radio" name="qtype" id="qtype" value="Web" required>Web
</label>
<label class="radio-inline">
<input type="radio" name="qtype" id="qtype" value="other" required>Other
</label>
</div>
</div>
<div class="form-group">
<textarea class="form-control" rows="3" name="text" id="text" required></textarea>
</div>
<button type="submit" class="btn btn-custom bleft" id="contact_query" name="contact_query">Submit</button>
First thing to try:
data: $('#contact_queryf').serialize()
instead of
data: $('contact_queryf').serialize()
(you were missing the #)
Also, you want to bind the click event to "#contact_query" (the submit button), not to the form itself, so
$('#contact_query').bind(...
instead of
$('contact_queryf').bind(...
$(function () {
$('#contact_queryf').on('click', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'Views/query_send.php',
data: $(this).serialize(),
success: function (response) {
// response
alert('form was submitted');
}
});
});
});
Take a look on the documentation - .on()
You are missing the # in your jquery selector
$('contact_queryf').bind('click', function (event) {
Should be
$('#contact_queryf').bind('click', function (event) {
The selector is incorrect, change the selector's
$(function () {
$('#contact_query').bind('click', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'Views/query_send.php',
data: $('#contact_queryf').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
OR
$(function () {
$('#contact_queryf').submit(function (event) {
$.ajax({
type: 'POST',
url: 'Views/query_send.php',
data: $(event.target).serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
And in HTML, form close </form> tag is missing
If you're using the <button type="submit" to submit the form you do not need the AJAX.
Or am I missing something?
Right now you're submitting the form when a user clicks the form.
Here you go cat daddy
This can get you jump started in submitting a form via AJAX but at a lower level.
This is really what you're attempting to do.
<button type="submit" class="btn btn-custom bleft" id="contact_query" name="contact_query" onclick="btnSubmitForm(event)">Submit</button>
var btnSubmitForm = function (event) {
event.preventDefault();
var newForm = new FormData(document.forms[0]),
xhr = new XMLHttpRequest(),
that = this;
xhr.onload = function () { /*do something when response is back from server*/ };
xhr.open('GET|POST|PUT|DELETE', 'YOUR URL', true);
xhr.send(newForm);
return false;
};