javascript (ASP.NET AJAX) refactor help - function not running - javascript

Here is the js file. The function SubmitCheck is running but when there is a state, I want to do the address check and it doesn't appear to run. What am I doing wrong?
Thanks,
ck in San Diego
var prm = null;
Sys.Application.add_init(Init);
function Init(sender) {
prm = Sys.WebForms.PageRequestManager.getInstance();
WireEvents();
}
function WireEvents() {
var submit = $("#btnSubmit");
submit.click(SubmitCheck);
}
function SubmitCheck(){
var hasState = DoStateCheck();
if (!hasState) {
prm.abortPostBack();
return false;
} else {
var addressCheck = DoAddressCheck();
alert(addressCheck);
}
if (!addressCheck) {
prm.abortPostBack();
return false;
}
}
function DoAddressCheck(){
var add1 = $("#txtAddressMaintLine1");
if (add1.val().length < 1) {
return confirm("No Address was detected.\nClick OK to proceed or Cancel to provide an address.");
}
return;
}
function DoStateCheck() {
var tb = $("#txtState");
if (tb.val().length < 2) {
alert("A state must be provided when establishing a claim.");
tb.focus();
return false;
}
return;
}

Maybe replace
return;
in DoStateCheck() with
return true;
?

Related

Place parts of a for loop into function in javascript

I have several functions that use this given for loop below.
function startClaw(dir){
var readCount = 0;
for(var isRead in qdata){
readCount++;
if(qdata[isRead]['reading'] == true){
return;
}else if(readCount == 5){
isAnimating = $("#claw").is(':animated');
if(!isAnimating){// prevents multiple clicks during animation
if(isMoving || isDropping){ return; }
MCI = setInterval(function(){ moveClaw(dir); },10);
//console.log("startClaw:" + dir);
stopSwingClaw();
}
}
}
}
//.................................................................
function dropClaw(){
var readCount = 0;
for(var isRead in qdata){
readCount++;
if(qdata[isRead]['reading'] == true){
return;
}else if(readCount == 5){
if(isDropping){ return; } //prevent multiple clicks
stopSwingClaw();
isDropping = true;
MCI = setInterval(moveDown,20); //start heartbeat
}
}
}
Everything in the else if statement is different within the various functions. I'm wondering if there is any way to place the "pieces" of the for loop on the outside of the else if into its very own function. I feel like I've seen this or had done this a very long time ago, but it escapes me and I couldn't find any examples. Thanks everyone!
Previewing, I see this is similar to the above. Two differences (it looks like) are here the count gets passed to the function in case they needed to ever have different checks in the if statement, and, it's checking what the return value is since it looks like you return out of the loop if the condition is met. There are notes in comments in the code below.
function startClaw(dir) {
// Pass a function as a callback to the method which expects to receive the count as a param
doReadCount(qdata, function(theCount) {
if (theCount === 5) {
isAnimating = $("#claw").is(':animated');
if (!isAnimating) { // prevents multiple clicks during animation
if (isMoving || isDropping) {
return true;
}
MCI = setInterval(function() { moveClaw(dir); }, 10);
//console.log("startClaw:" + dir);
stopSwingClaw();
}
return false;
});
}
//.................................................................
function dropClaw() {
// Pass a function as a callback to the method which expects to receive the count as a param
doReadCount(qdata, function(theCount) {
if (theCount === 5) {
if (isDropping) {
return;
} //prevent multiple clicks
stopSwingClaw();
isDropping = true;
MCI = setInterval(moveDown,20); //start heartbeat
}
});
}
function doReadCount(qdata, elseFunction) {
var readCount = 0;
var elseReturn;
for (var isRead in qdata) {
readCount++;
if (qdata[isRead]['reading'] == true) {
return;
} else {
// call the function that was sent and pass it the current read count. If the return is true, then also return true here
elseReturn = elseFunction(readCount);
if (elseReturn) {
return;
}
}
}
}
You can pass a function into another function to achieve this. I've done it for dropClaw, and it should be clear from my example how to do also extract startClaw.
function operateClaw(func){
var readCount = 0;
for(var isRead in qdata){
readCount++;
if(qdata[isRead]['reading'] == true){
return;
}else if(readCount == 5){
func();
}
}
}
function drop () {
if(isDropping){ return; } //prevent multiple clicks
stopSwingClaw();
isDropping = true;
MCI = setInterval(moveDown,20); //start heartbeat
}
function dropClaw () {
operateClaw(drop);
}

JavaScript Returns from Functions. Functions calling functions

I am trying to get a better understanding on javacsript. And I am not sure why this code is not working. I am trying to create functions that will call another function. And return the results of the called function.
When I call the below, I get fully logged in and presented with the screen I desire. But jsDidLogin Always returns undefined. Is there a better way to implement my methods?
var jsDidLogin = beginLogin()
console.log(jsDidLogin)
function waitUntilElementFound(element, time, callFunction) //Wait for the element to be found on the page
{
if (document.querySelector(element) != null) {
return callFunction();
}
else {
if (!checkForFailedLogin()) {
setTimeout(function () {
waitUntilElementFound(element, time, callFunction);
}, time);
}
else {
return false;
}
}
}
function checkForFailedLogin() {
if (document.querySelector("div[class='modal-body ng-scope'] h1") != null) {
if(document.querySelector("div[class='modal-body ng-scope'] h1").innerHTML == "Login Error")
{
return true;
}
}
else {
return false;
}
}
function initialTabSelect() //Load the bank page once login is completed
{
document.querySelectorAll("li[class='Tab'] a")[0].click();
return "Fully Logged In";
}
function initialDoNotAsk() {
document.querySelectorAll("a[ng-click='modalCancel()']")[0].click();
return waitUntilElementFound("li[class='Tab'] a", 1000, initialTabSelect);
}
function initialLogin() {
var accountName = document.getElementById("username");
var accountPassword = document.getElementById("password");
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
accountName.value = "USERNAME";
accountPassword.value = "PASSWORD";
accountName.dispatchEvent(evt);
accountPassword.dispatchEvent(evt);
document.querySelectorAll("form[name='loginForm'] button.icon-login")[0].click();
return waitUntilElementFound("a[ng-click='modalCancel()']", 2000, initialDoNotAsk);
}
function beginLogin() {
return waitUntilElementFound("form[name='loginForm'] button.icon-login", 1000, initialLogin);
}
Changing to this alerts me when Fully Logged in, but if I change it to return status. I still get no returns.
My head is starting to hurt :(
function waitUntilElementFound(element, time, callFunction, callBack) //Wait for the element to be found on the page
{
if (document.querySelector(element) != null) {
callBack(callFunction());
}
else {
if (!checkForFailedLogin()) {
setTimeout(function () {
callBack(waitUntilElementFound(element, time, callFunction, function(status){alert(status);}));
}, time);
}
else {
return false;
}
}
}
function checkForFailedLogin() {
if (document.querySelector("div[class='modal-body ng-scope'] h1") != null) {
if(document.querySelector("div[class='modal-body ng-scope'] h1").innerHTML == "Login Error")
{
return true;
}
}
else {
return false;
}
}
function initialTabSelect() //Load the bank page once login is completed
{
document.querySelectorAll("li[class='Tab'] a")[0].click();
return "Fully Logged In";
}
function initialDoNotAsk() {
document.querySelectorAll("a[ng-click='modalCancel()']")[0].click();
return waitUntilElementFound("li[class='Tab'] a", 1000, initialTabSelect, function(status){alert(status)};);
}
function initialLogin() {
var accountName = document.getElementById("username");
var accountPassword = document.getElementById("password");
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
accountName.value = "USERNAME";
accountPassword.value = "PASSWORD";
accountName.dispatchEvent(evt);
accountPassword.dispatchEvent(evt);
document.querySelectorAll("form[name='loginForm'] button.icon-login")[0].click();
return waitUntilElementFound("a[ng-click='modalCancel()']", 2000, initialDoNotAsk, function(status){alert(status)};);
}
function beginLogin() {
return waitUntilElementFound("form[name='loginForm'] button.icon-login", 1000, initialLogin, function(status){alert(status)};);
}

Stripe JavaScript showing live mode when in test mode in Rails 4

As you can see from the attached segments below I am running in testing mode and when I try to use the testing stripe cards specifically 4242424242424242 nothing is working. How can I debug this?
Console log of the Stripe error:
Stripe interface:
The JavaScript code in progress:
function process_payment(cardNumber, cardExpiration, cardVerification, zipCode, price){
var vpf = validate_payment_fields();
if(vpf === true){
process_stripe_api(cardNumber, cardExpiration, cardVerification, zipCode, price);
// $contentLoader.show();
// clear_cc_fields($cardNumber, $cardExpiration, $cardVerification, $zipCode);
// $paymentProcessorForm.submit();
}
}
function process_stripe_api(cardNumber, cardExpiration, cardVerification, zipCode, price){
Stripe.createToken({
number: cardNumber,
cvc: cardVerification,
exp_month: cardExpiration.substring(0,2),
exp_year: cardExpiration.substring(3,5),
price: price
}, stripeResponseHandler);
}
function stripeResponseHandler(status, response) {
if (response.error) {
debugger;
}
else {
console.log('passed!');
debugger;
}
}
function validate_payment_fields(){
var $cardNumber = jQuery('#card_number');
var $cardVerification = jQuery('#card_verification');
var $cardExpiration = jQuery('#card_expiration');
var $zipCode = jQuery('#zip_code');
$cardNumber.next('.help-error').remove();
$cardVerification.next('.help-error').remove();
$cardExpiration.next('.help-error').remove();
$zipCode.next('.help-error').remove();
trim_field($cardNumber);
var cardNumber = validate_card_number($cardNumber);
trim_field($cardExpiration);
var cardExpiration = validate_card_expiration($cardExpiration);
trim_field($cardVerification);
var cardVerification = validate_card_verification($cardVerification);
trim_field($zipCode);
var zipCode = validate_zipcode($zipCode);
if(cardNumber && cardExpiration && cardVerification && zipCode){
return true;
}
else{
return false;
}
}
function clear_cc_fields(cardNumber, cardExpiration, cardVerification, zipCode){
cardNumber.val('');
cardVerification.val('');
cardExpiration.val('');
zipCode.val('');
}
function validate_card_number(field){
var regTester = new RegExp("\\d{16}");
if(regTester.test(field.val())){
return true;
}
else{
field.after("<p class='help-error'>Credit Card Number is Invalid!</p>");
return false;
}
}
function validate_card_expiration(field){
var regTester = new RegExp("^((0[1-9])|(1[0-2]))\/((2009)|(20[1-2][0-9]))$");
if(regTester.test(field.val())){
return true;
}
else{
field.after("<p class='help-error'>Credit Card Expiration is Invalid!</p>");
return false;
}
}
function validate_card_verification(field){
var regTester = new RegExp("\\d{3}");
if(regTester.test(field.val())){
return true;
}
else{
field.after("<p class='help-error'>CCV is Invalid!</p>");
return false;
}
}
function validate_zipcode(field){
var regTester = new RegExp("\\d{5}");
if(regTester.test(field.val())){
return true;
}
else{
field.after("<p class='help-error'>Zip Code is Invalid!</p>");
return false;
}
}
function trim_field(field){
var tmp = jQuery.trim(field.val());
field.val(tmp);
return tmp;
}
A snippet from the view:
= javascript_include_tag 'https://js.stripe.com/v2/'
javascript:
Stripe.setPublishableKey("#{ENV['MY_STRIPE_PUBLISHABLE_KEY']}");
The form:
Make sure the Stripe key you're using is the test key and not the production key:
Your key should start with pk_test or sk_test

Function set to run once not running

Happy Holidays! How do i get this function running? I can see the console.log running on the mouse wheel, however the function set to run once does not run. On the start i have also made sure that the body contains both the required classes.
var $body = $('body');
//using index
if(index == 2){
$body.css({
overflow: 'hidden'
});
if($body.hasClass('fp-viewing-secondPage')) {
$('html').on('mousewheel', function (e) {
console.log('fucks');
var delta = e.originalEvent.wheelDelta;
if($body.hasClass('setAn1')){
var something = (function() {
var secret = false;
return function () {
if(!secret){
console.log('call me once please an1');
secret = true;
}
};
});
something();
}
if($body.hasClass('setAn2')){
var something2 = (function() {
var secret = false;
return function () {
if(!secret){
console.log('call me once please an2');
secret = true;
}
};
});
something2();
}
});
}
}
var something = (function() {
var secret = false;
return function () {
if(!secret) {
console.log('call me once please an1');
secret = true;
}
};
})();
You have the above block which is an IIFE. I believe what it's doing is assigning the below function to the something variable.
function () {
if(!secret) {
console.log('call me once please an1');
secret = true;
}
You'd have to then call the something() here.
secret = true;
}
};
})();
something();
}
I ported the structure of your program over into jfiddle. Your primary problem is that you're modifying a value who was defined inside of the scope created by the definition of the function. This value only lasts as long as that function is currently executing, once you leave the function the value leaves scope. What you need to do is define the variable outside the scope of the function so that you won't lose the state you're trying to keep between clicks.
Here's a minimal example. You'll see the secret gets set once you go through the loop, and then prevents the function's if() condition from being evaluated again.
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
var secret = false;
$('img').on('click', function(e) {
console.log('what is my secret outside?', secret);
if (!secret) {
console.log('what is my secret inside?', secret);
secret = true;
}
});
https://jsfiddle.net/wa819y2j/9/
var something = (function() {
var secret = false;
return function () {
if(!secret){
console.log('call me once please an1');
secret = true;
}
};
});
var something2 = (function() {
var secret = false;
return function () {
if(!secret){
console.log('call me once please an2');
secret = true;
}
};
});
var $body = $('body');
//using index
if(index == 2){
$body.css({
overflow: 'hidden'
});
if($body.hasClass('fp-viewing-secondPage')) {
$('html').on('mousewheel', function (e) {
console.log('fucks');
var delta = e.originalEvent.wheelDelta;
if($body.hasClass('setAn1')){
something();
}
if($body.hasClass('setAn2')){
something2();
}
});
}
}
Or else:
function runOnce(fun) {
var secret = false;
return function () {
if(!secret){
fun();
secret = true;
}
};
}
var something = runOnce(function() {
console.log('call me once please an1');
});
var something2 = runOnce(function() {
console.log('call me once please an2');
});

Why is my jQuery/Javascript function not being called correctly with onsubmit?

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.
I tried fixing it two ways. One way was like this, splitting them into two functions:
var fullString = "";
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";
}
fullString = s;
});
function validateNewQuiz()
{
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
}
And the second way, by added the return outside of the CSV part:
var fullString = "";
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";
}
fullString = s;
});
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
}
Does anyone have any suggestions to why my form is always submitting, even when my function should be returning false?
Here is another edit that I tried to make, although it is still submitting to my PHP and the console messages are not being displayed since that page is being submitted to PHP, therefore reloading
jQuery("#newQuizID").click(function(e)
{
e.preventDefault();
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))
{
console.log("Working");
jQuery("#form-step2").submit();
}
else
{
console.log("Not Working");
}
});
});
html5csv puts a event handler on the file input so it only triggers when a file is added so you need to set a valid flag somewhere and then check it before submitting
function checkValidCSV(e) {
var isValid = jQuery("#form-step2").data("hasValidData");
if( typeof(isValid) != "undefined" && isValid ) {
jQuery("#form-step2").submit();
} else {
//Do whatever invalid data cals you want to do here
alert("csv file was invalide so i am not submitting the form");
e.preventDefault();
}
}
function csvFileLoaded(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)){
console.log("Valid Data");
jQuery("#form-step2").data("hasValidData",true);
} else {
console.log("Invalid Data");
jQuery("#form-step2").data("hasValidData",false);
}
}
jQuery(document).ready(function() {
CSV.begin("#upload_csv").go(csvFileLoaded);
jQuery("#newQuizID").click(checkValidCSV);
});

Categories