I have defined a div within which a form with default input values is appended based on MySQL table data returned by PHP via an ajax $.get call.
The div looks like:
<div id="esfContainer1">
</div> <!--end esfContainer1 div-->
The div is absolutely positioned relative to the body tag.
The script associated to the form validation broke when it was included on the main page where the call to the form was being made, so I moved it to the PHP output $formContent.
Here is the form validation and submit script included in the PHP output:
<script type="text/javascript">
var senderName = $("#sendName");
var senderEmail = $("#fromemailAddress");
var recipientEmail = $("#toemailAddress");
var emailError = $("#esemailerrorDiv");
senderName.blur(checkName);
senderEmail.blur(checkSEmail);
recipientEmail.blur(checkREmail);
function checkName() {
if (senderName.val() == "YOUR NAME") {
$("#esemailerrorText").html("Please provide your name");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
} else {
return true;
}
};
function checkSEmail() {
var a = senderEmail.val();
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(a)) {
return true;
} else {
$("#esemailerrorText").html("Please enter a valid email address");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
}
};
function checkREmail() {
var a = recipientEmail.val();
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(a)) {
return true;
} else {
$("#esemailerrorText").html("Your friend\'s email is invalid");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
}
};
$("#emailForm").submit (function() {
if (checkName() && checkSEmail() && checkREmail()) {
var emailerData = $("#emailForm").serialize();
$.get("style.php",emailerData,processEmailer).error("ouch");
function processEmailer(data) {
if (data=="fail") {
return false;
} else if (data=="pass") {
$("#c1Wrapper").fadeOut("slow","linear");
$("#confirmation").fadeIn("slow","linear");
$("#esfContainer1").delay(2000).fadeOut("slow","linear");
$("#backgroundOpacity").delay(2000).fadeOut("slow","linear");
return false;
}
};
return false;
};
return false;
});
I have splatter-bombed the above submit function with "return false;" because the submit function has been simply opening the processing PHP script rather than executing the $.get. Watching the submit function with Firebug reports that processEmailer is undefined.
I am very new to this. I was assuming that because the ajax callback is being defined within the submit function (and that the processEmailer function is defined directly below the ajax call) that there wouldn't be a problem with definition.
Thanks in advance for any help.
You've been trapped by function statements. Function declarations (which would be hoisted) are not allowed inside blocks (if/else/for bodies) and if they are appear there, behaviour is not defined. Firefox defines them conditionally, and in your case after you've used it in the $.get call - where it was undefined then - like in var functionName = function() {} vs function functionName() {}.
To solve this, simple put it outside the if-block (or even outside the whole callback). Btw, .error("ouch") won't work, you need to pass a function.
$("#emailForm").submit (function() {
if (checkName() && checkSEmail() && checkREmail()) {
var emailerData = $("#emailForm").serialize();
$.get("style.php",emailerData).done(processEmailer).fail(function() {
console.log("ouch");
});
}
return false;
// now a proper function declaration, will be hoisted:
function processEmailer(data) {
if (data=="fail") {
return false;
} else if (data=="pass") {
$("#c1Wrapper").fadeOut("slow","linear");
$("#confirmation").fadeIn("slow","linear");
$("#esfContainer1").delay(2000).fadeOut("slow","linear");
$("#backgroundOpacity").delay(2000).fadeOut("slow","linear");
return false;
}
}
});
Related
I am beginer in js, and i have problem with merge two fucntions. I want to make third function with condition, when checkbox is marked and reCAPTCHA is marked, only then button is enable. By default, i set the button to disabled.
Single functions as below is working:
function clauseValid(elem) {
document.getElementById("sendBtn").disabled = false;
return true;
};
function captchaValid () {
document.getElementById("sendBtn").disabled = false;
return true;
};
<input type="checkbox" name="chkbx" id='#ID#' value="#seq_claim_id#" onClick="clauseVlid(this)">
<div class="g-recaptcha" data-sitekey="*****..." id="ckecCaptcha" type="checkbox" data-callback="captchaValid"></div>
I tried make someone like this but it doesn't work:
function clauseValid(elem) {
return true};
function captchaValid() {
return true};
function CheckTest() {
if (clauseValid(elem) && captchaValid()) {
document.getElementById("sendBtn").disabled = false;
}
}
Use variables for keeping track of the current status of each condition:
let isClauseValid, isCaptchaValid;
function clauseValid(elem) {
isClauseValid = elem.checked;
setButton();
}
function captchaValid() {
isCaptchaValid = true;
setButton();
}
function setButton() {
document.getElementById("sendBtn").disabled = !isClauseValid || !isCaptchaValid;
}
NB: make sure to correct the spelling mistake in your HTML onclick attribute.
I have this cute class:
validations.js
var Validation = function () {
var load= function () {
$.validator.addMethod("noweirdstuff", function (value, element) {
return !(/\W/.test(value));}, "Username has invalid characters. Only letters, numbres & underscores allowed.");
$.validator.unobtrusive.adapters.add("noweirdstuff", function (options) {
options.rules["noweirdstuff"] = true;
if (options.message) { options.messages["noweirdstuff"] = options.message;}
});
}
return {
init: function () {
load();
}
};
}();
validations.js is bundled and minified with all javascript code into single file. Then, I'm using per page script to load only required code. In this case:
Validation.init();
But it doesn't seem fire the validation. I'm 100% sure that Validation.init() is being called.
It only works when I take it outside:
validations.js
var Validation = function () {
var load = function () {
// goodbye adding validation
}
return {
init: function () {
load();
}
};
}();
$.validator.addMethod("noweirdstuff", function (value, element) {
return !(/\W/.test(value));}, "Username has invalid characters. Only letters, numbres & underscores allowed.");
$.validator.unobtrusive.adapters.add("noweirdstuff", function (options) {
options.rules["noweirdstuff"] = true;
if (options.message) { options.messages["noweirdstuff"] = options.message;}
});
Why?
This is because you are registering your custom script validators after the page is loaded. The validation rules are applied to the whole document once unobtrusive validator loads, if your rules and validators haven't been added to the stack by then, they will be ignored.
I believe you could call $.validator.unobtrusive.parse(document) after you have added your rules and validators, I'm not 100% sure this would work or if would apply validators twice.
Edit: Rephrased the answer
Edit: Added possible solution
How to hide and show the default Javascript alert in the same HTML Page.
For example:
In function_one I want to hide the Javascript default alert
function function_one() {
//hide Javascript alert
}
In function_two I want to show the default Javascript which has been hidden in function_one
function function_two() {
//show Javascript alert
}
Both Javascript functions are in the same HTML page.
If you want to prevent calls to alert() from being displayed, use the following code:
var defaultAlert = null;
function function_one() {
if (defaultAlert === null) {
defaultAlert = window.alert;
window.alert = function() {};
}
}
function function_two() {
if (defaultAlert !== null) {
window.alert = defaultAlert;
defaultAlert = null;
}
}
You can disable it by overriding its value with an empty function. You store the old value in a variable (oldAlert) and then restore it assigning the old value back to window.alert:
function function_one() {
oldAlert = window.alert;
window.alert = function() {};
}
function function_two() {
window.alert = oldAlert;
}
I have this jQuery function that is using another jQuery library called html5csv.js (which explains some of the CSV stuff you will see)
Here is it:
function validateNewQuiz()
{
CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
}
Here is how I am trying to call my function, from an onsubmit within my form:
<form method="post" action="createplay.php" onsubmit="return validateNewQuiz();" enctype="multipart/form-data">
My function has been thoroughly tested, along with my regex to make sure it was working. When I decided to implement it into my large document, and wrap it around function validateNewQuiz(){ //my function here } , it stopped working.
I did not make my tests with the onsubmit part within my form either.
Does anyone have any suggestions to why my form is always submitting, even when my function should be returning false?
The onsubmit event handler allows the submission to proceed if it is passed a true value by the validation function, and does not allow the submission to proceed if it receives a false value. In your case, the inner function is returning a true or false value, but this value is not being passed to the outer validateNewQuiz function, so the true/false result of the validation is not being passed to the onsubmit event handler. To fix this, just return the value of the CSV function.
function validateNewQuiz()
{
var csvValidation = CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
return csvValidation;
}
You can make a button that would be calling your function:
<button onclick="validateNewQuiz()">Submit</button>
... and submitting the form once it is validated:
function validateNewQuiz()
{
CSV.begin("#upload_csv").go(function(e,D)
{
//...
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
$("form").submit();
}
});
return false;
}
I have a jquery function that is triggered by a button click. When it then calls a javascript function that returns true however, jquery claims the value is undefined.
function mytrue()
{
alert ("true is returned");
return true;
}
$('#save').click(function()
{
var response = mytrue();
if (response) {
alert ("This should work!");
} else
{
alert ("This is puzzeling? "+response);
}
}
I get the "true is returned" alert and the "This is puzzeling? undefined" alert.
I believe you just forgot the trailing ) parenthesis after your $('#save')... function
Here is a link to a jsfiddle of your code that works: http://jsfiddle.net/ZswU8/
Here's the problem I'm having. I know it's a scope thing, but I'm not sure how to get around it.
http://jsfiddle.net/k5h52/12/
var a = {
mytrue:function()
{
alert ("true is returned");
return true;
}
}
var b = {
init:function(){
$('#save').click(function()
{
var f = function(){a.mytrue()};
var response = f();
if (response) {
alert ("This should work!");
} else
{
alert ("This is puzzeling? "+response);
}
});
}
}
b.init();