Why is my jQuery function not being called correctly? - javascript

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;
}

Related

How to merge two javascript function with third function with condition?

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.

Listen for keyup on all input fields

Im trying to capture the keyup on all input fields on a page.
My current code is:
var els = document.querySelectorAll('input');
for (var i = 0; i < els.length; i += 1) {
addEvent('keyup', els[i], makeHandler(els[i]));
}
function makeHandler(field) {
console.log(field.value);
}
function addEvent(evnt, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) {
elem.attachEvent("on"+evnt, function(e) {
e = e || window.event;
if (!e.preventDefault) {
e.preventDefault = preventDefaultOnIE;
}
func.call(this, e);
});
} else { // No much to do
elem[evnt] = func;
}
}
But for some reason its only capturing the value on page load, not once i begin to type in any of the fields.
Any ideas what I'm doing wrong?
The problem is with your makeHandler function. makeHandler(els[i]) is being evaluated and the return value (undefined, in this case) is being passed to addEvent as a handler. Try:
function makeHandler(field) {
return function() {
console.log(field.value);
};
}
This way, makeHandler(els[i]) will return a function that addEvent can then attach to keyup.
Alternatively, you could also just use:
function makeHandler() {
console.log(this.value); // 'this' will be the field that the event occurred on
}
and then use:
addEvent('keyup', els[i], makeHandler);
Side-note
I noticed a slight error in your code:
else { // No much to do
elem[evnt] = func;
}
I think you really want to set elem["on" + evnt] instead.
I like to embed the script in a function so I can minimize it in my IDE and turn it on and off globally. In other words, give it a name.
attachKeyupListenerToInputElements();
function attachKeyupListenerToInputElements(){
var inputs = doc.querySelectorAll('input');
for (var i = 0; i < inputs.length; i += 1) {
inputs[i].addEventListener("keyup", keyupHandler);
}
function keyupHandler() {
console.log(this.value);
}
}
Is this what you are looking for:
<script>
$(document).ready(function () {
$("input").keyup(function () {
alert("keyup");
});
});
</script>

ajax $.get callback reported as undefined

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;
}
}
});

Jquery check if var is a function and then call it

I have a variable name that I pass into a plugin, but the variable is actually a function.
I use jquery $.isFunction to check if it is a function, and if it is, it should execute the function.
But I can't seem to make it work, I put some examples in jsfiddle:http://jsfiddle.net/tZ6U9/8/
But here is a sample code:
HTML
<a class="one" href="#">click</a><br />
<a class="two" href="#">click</a><br />
<a class="three" href="#">click</a><br />
JS
$(document).ready(function() {
help = function(var1) {
alert(var1);
}
function help2(var1) {
alert(var1);
}
$('a.one').click(function() {
var functionName = "help";
if ($.isFunction([functionName])) {[functionName]("hello");
} else {
alert("not a function");
}
return false;
});
$('a.two').click(function() {
var functionName = "help";
if ($.isFunction(functionName)) {
functionName("hello");
} else {
alert("not a function");
}
return false;
});
$('a.three').click(function() {
var functionName = "help2";
if ($.isFunction(functionName)) {
functionName("hello");
} else {
alert("not a function");
}
return false;
});
$('a.four').click(function() {
var functionName = "help2";
if ($.isFunction([functionName])) {[functionName]("hello");
} else {
alert("not a function");
}
return false;
});
});​
As you can see, I tired a bunch of things, but all the wrong ones probably...
I inspired some of them from: jQuery - use variable as function name
Overall
I'm passing a variable that has the same name as a function, using jquery to check if it is a function, if it is, it should execute the function.
Thanks in advance for your help.
If you are wanting to call a function by a string of its name just use window.
var functionName = "help";
if ($.isFunction(window[functionName])) {
window[functionName]("hello");
} else {
alert("not a function");
}
You can use the following to invoke functions that are defined in the window/global scope, such as the function help:
if ($.isFunction(window[functionName])) {
window[functionName]("hello");
}
help2, on the other hand, is not accessible this way since you are defining it in a closure. A possibile solution is to define the function outside of the .ready() handler. Then, you can use window[functionName] to call it:
var namespace = {
help: function (var1) {
alert(var1);
},
help2: function (var1) {
alert(var1);
}
}
$(document).ready(function() {
var functionName = "help";
if ($.isFunction(namespace[functionName])) {
namespace[functionName]("hello");
}
});
DEMO.
Check Fiddle for the working example.
Example have only one link working. make other links similarly.
Edit: after first comment
HTML
<a class="one" href="#">click</a><br />
JS
var help = function(var1) {
alert(var1);
}
$(document).ready(function() {
$('a.one').click(function() {
var functionName = help;
if ($.isFunction(functionName)) {
functionName('test');
} else {
alert("not a function");
}
return false;
});
});​

Javascript.. problem with value by reference possibly

The problem here is that page at alert has the final value of i.. any solution to this?
for(var i=start;i<=end;i++)
{
num=pageNumber.clone();
num.click(function(event)
{
event.preventDefault();
var page=i;
alert(page);
// drawPager();
});
num.find("span").text(i);
if(i==curPage) {
num.find("span").addClass("current");
num=num.find("span");
}
$("#pager>div").append(num);
}
You should do something like this:
num.click(function(i) {
return function(event) {
event.preventDefault();
var page = i;
alert(page);
}
}(i));
This would make an extra enclosure, so i wouldn't get overwritten.
You need to add the handler in a separate function that takes i as a parameter.
For example:
for(var i=start;i<=end;i++) {
handlePage(i);
}
function handlePage(i) {
num=pageNumber.clone();
num.click(function(event)
{
event.preventDefault();
var page=i;
alert(page);
// drawPager();
});
num.find("span").text(i);
if(i==curPage) {
num.find("span").addClass("current");
num=num.find("span");
}
$("#pager>div").append(num);
}
This way, a separate closure (with a separate i parameter) will be generated for each function call.

Categories

Resources