I am pretty new to javascript.
Working on a wordpress I typed the following function in the custom js for my theme:
document.getElementsByName("empty_cart")[0].onclick = function(e) {
var choice = confirm("Are You Sure ?");
if (!choice) {
//Cancel submit
e.preventDefault();
}
};
This script allows for an "Are you sure you want to empty the cart?" confirmation, and works fine.
but when I added the following script that I copy and pasted from my email campaign provider ( robly ) the "are you sure" confirmation stopped working.
$(document).ready(function () {
$("#robly_embedded_subscribe").click(function (e) {
e.preventDefault();
var email = $("#DATA0").val();
if (!is_valid_email_address(email)) {
alert("Please enter a valid email address.");
return false;
}
var f = $("#robly_embedded_subscribe_form");
f.submit();
return false;
});
});
function is_valid_email_address(emailAddress) {
var pattern = new RegExp(/^((([a-z]|d|[!#$%&'*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+(.([a-z]|d|[!#$%&'*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+)*)|((x22)((((x20|x09)*(x0dx0a))?(x20|x09)+)?(([x01-x08x0bx0cx0e-x1fx7f]|x21|[x23-x5b]|[x5d-x7e]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([x01-x09x0bx0cx0d-x7f]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))))*(((x20|x09)*(x0dx0a))?(x20|x09)+)?(x22)))#((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).?$/i);
return pattern.test(emailAddress);
}
I have attempted to remove the function is_valid snippet and move that to my functions.php file in my child theme... but that didn't work.
If anyone could help me out I would really appreciate it.
If you need any further information from me, please ask.
Often times with WordPress you need to change all instances of $ to jQuery
For example:
$(document).ready(function () { ... });
would become:
jQuery(document).ready(function () { ... });
Related
So I'm using Bootstrap 4 for my project, and I really like the way their validation works for each input element in a form. I'm using this code to validate my form, this was off their website:
<script>
(function () {
"use strict";
window.addEventListener(
"load",
function () {
// Fetch all the forms we want to apply custom Bootstrap 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
);
})();
</script>
The only thing is, in my javascript file, I have another listener that's supposed to get fired when the sign-up button is submitted inside my form. For whatever reason, even once all the input fields are validated, I can't get it to call my submit function. Here's the code inside my javascript file:
document.addEventListener("DOMContentLoaded", function() {
initApp();
});
function initApp() {
document.querySelector("#sign-up").addEventListener("submit", createAccount, false);
}
function createAccount() {
alert('test');
}
I've tried a bunch of stuff like moving this validation code before and after the initialization of my js file, but nothing worked. The goal is to have 2 submit buttons in this form (one is sign up, other is log in) and depending which one is pressed, a different function should be called. If anyone has any ideas, I'd appreciate it!
So if anyone was interested, I fixed my problem by changing the button from submit to a regular button and running validation through my own code. Here's the fiddle of it: https://jsfiddle.net/bv84ncz5/
var forms = document.getElementsByClassName("needs-validation");
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.classList.add("was-validated");
});
let password = document.querySelector("#password");
let email = document.querySelector("#email");
if (password.checkValidity() === true && email.checkValidity() === true) {
alert("sup");
}
The only thing you need for Bootstrap validation to work is add the class was-validated to each input in the form. Then, you can check if all the forms you want are valid with checkValidity(), and then carrying out what else you want to do
As I stated in my comment, I'm not sure what are you doing wrong, must be something. Check this scriptlet working, I changed nothing from you code, I just put it together.
document.addEventListener("DOMContentLoaded", function() {
initApp();
});
function initApp() {
document.querySelector("#sign-up").addEventListener("submit", createAccount, false);
}
(function () {
"use strict";
window.addEventListener(
"load",
function () {
// Fetch all the forms we want to apply custom Bootstrap 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 createAccount() {
alert('test');
}
<form id="sign-up">
<input type="text" class="needs-validation" />
<input type="submit" />
</form>
I have a webpage that opens a modal form. I validate the modal form using a JQuery function. The problem is that my function is checking all fields in both the modal AND the page behind it.
//validate function
function validateFields() {
var valid = true;
$('.required').each(function () {
if (!$(this).val()) {
addError(this, 'required');
valid = false;
}
});
}
//in my save function
function saveLead(){
if (validateFields()) {
//save
}
}
My validate function is checking all fields with the required class on both my page and modal. How can I get it to just use my page?
UPDATE:
this has complications because my validation function is reused on many pages and is not set up to accept a specific form to check
Is such a thing possible or do I have to do major revisions to the validation or modal in order for this to work?
You could detect the form from which the submit button is clicked. Something like the below should work.
//validate function
function validateFields($submittedForm) {
var valid = true;
$('$submittedForm .required').each(function () {
if (!$(this).val()) {
addError(this, 'required');
valid = false;
}
});
}
//in my save function
// Find the form there 'this' is the submit button
var $submittedForm = $(this).closest('form');
function saveLead($submittedForm){
if (validateFields($submittedForm)) {
//save
}
}
Basic form of the code is given below that i want rectified. while running the code once it reaches .show() function the page is getting refreshed. I don't want that. Can you help me with this dilemma!!!!
Please see the code below :
Code:
$(document).ready(function() {
$("#mandate").hide();
$("#submit").click(function() {
var password = $("#password").val();
if(password=='') {
$("#mandate").show();
}
else {
alert("Form Submitted Successfully..!!");
}
}
}
HTML:
<p id="mandate"><font color="red">Password is mandatory*</font></p>
Add return false; to your code.
$(document).ready(function() {
$("#mandate").hide();
$("#submit").click(function() {
var password = $("#password").val();
if(password=='') {
$("#mandate").show();
return false;
}
else
{
alert("Form Submitted Successfully..!!");
}
});
The return false will return false to the event. That tells the browser to stop following events, like follow a link. It is similar to event.preventDefault()
I have JavaScript code that checks if all the fields in a form are filled, if not it pops up a bootstrap alert using jquery. This works fine with text inputs, but when checking selects, it always fires the error, even if an option is filled.
JavaScript Code:
$(document).ready(function () {
$('form[name="register"]').on("submit", function (e) {
var username = $(this).find('input[name="username"]');
var preferredClass = $(this).find('input[name="preferredClass"]');
if ($.trim(username.val()) === "" || ($.trim(preferredClass.val())) === "") {
e.preventDefault();
$("#formAlert").slideDown(400);
} else {
$("#formAlert").slideUp(400, function () {});
}
});
$(".alert").find(".close").on("click", function (e) {
e.stopPropagation();
e.preventDefault()
$(this).closest(".alert").slideUp(400);
});
});
The entire code and (Kind of) working example can be found in this JSFiddle.
you have wrong selector for your select
Replace this
var preferredClass = $(this).find('input[name="preferredClass"]');
With this:
var preferredClass = $(this).find('select[name="preferredClass"]');
Working Demo
Your select element selector is wrong.
Try to change the selector statement:
$(this).find('select[name="preferredClass"]');
Then your validation will be ok.
Hope this is helpful for you.
I am using jQuery to validate some fields in a form, and seem to be having an issue with one field in particular (#inputTel).
If an incorrect format is entered, an error message pops up underneath, which is fine, but the problem is once the correct format is entered the message does not disappear.
Here's a jsFiddle with the complete demo.
This is the section in question:
//Tel Validate
function is_valid_tel() {
$this = $("#inputTel");
var pattern = new RegExp("^\d{11}$");
if (pattern.test($this.val())) { // valid
if ($this.closest(".control-group").hasClass("error")) $this.closest(".control-group").removeClass("error");
$this.siblings(".help-inline").css("display", "none");
return true;
} else { // error
if (!$this.closest(".control-group").hasClass("error")) $this.closest(".control-group").addClass("error");
$this.siblings(".help-inline").css("display", "block");
return false;
}
}
Every other field works as expected except this one. My jQuery skills are limited so I'm unsure of how to solve this.
Problem in your code:
Replace var pattern = new RegExp("^\d{11}$"); with var pattern = new RegExp(/^\d{11}$/);
Updated code
//Tel Validate
function is_valid_tel() {
$this = $("#inputTel");
var pattern = new RegExp(/^\d{11}$/);// Update this line
if (pattern.test($this.val())) { // valid
if ($this.closest(".control-group").hasClass("error")) $this.closest(".control-group").removeClass("error");
$this.siblings(".help-inline").css("display", "none");
return true;
} else { // error
if (!$this.closest(".control-group").hasClass("error")) $this.closest(".control-group").addClass("error");
$this.siblings(".help-inline").css("display", "block");
return false;
}
}
Check the fiddle http://jsfiddle.net/rfg8H/
You could also use something like below, less cubersome:
$(function() {
function validateTheForm() {
var ok = true;
$(".input-medium").each(function() {
if($(this).val() == "") //use regex actually here
{
$(this).next().css("display","inline");
ok = false;
}
else {
$(this).next().css("display","none");
}
});
return ok;
}
$(".btn").click(function() {
$("form").submit(validateTheForm());
$("form").submit();
});
});