Javascript while loop in FTL page - javascript

I am validating the drop down lists selections on the FTL page. I could not make it to work on the click function on submit button, so I am trying to enable/disable the submit button until some selection is made in both drop down lists. I am using while loop for that and it is not working. Both javascript and FTL pages are new to me. Please help.
document.getElementById("add_officevisits_button").disabled = true;
var ddvalid= false;
// loop until all is validated
do {
ddvalid = validate_dropdownlists();
}
while (ddvalid = false) ;
// if yes, let the user proceed
if (ddvalid) {
//$j('#add_officevisits_button').show();
document.getElementById("add_officevisits_button").disabled = false;
}
function validate_dropdownlists(){
var validated =false;
// visittype
var visittype = false;
if ($j('#officevisits_visitTypeID').val() == "") {
visittype = false;
}
else {
visittype = true;
}
validated = visittype;
//outcome
var OutcomeValid = true;
if ($j('#officevisits_visitOutcomeID').val() == "") {
OutcomeValid = false;
}
else {
OutcomeValid = true;
}
validated = OutcomeValid && validated;
return validated;
}

Related

Email validation and not letting the visitor to pass if the email is invalid

We have a Shopify store and i have a script which validates the email adress and writes out if the email address is not good, another script is checking if the form is filled out and if it's not - it's not letting the customer to pass the next stage based on ID selector.
I only need this email validator to do the same thing as the other script, write out an alert when the email address is not correct and don't let them pass to the next step.
Can someone help with this? How to do that?
Script which validates the email address:
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
if (validateEmail(email)) {
$result.text(email + ' e-mail address is valid!');
$result.css('color', 'green');
} else {
$result.text(email + ' Lūdzu, ievadiet derīgu e-pastu lai pabeigt pirkumu');
$result.css('color', 'red');
}
return false;
}
$('#email').on('input', validate);
Script which checks wheter the form was filled out or not:
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
})
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
}
};
Appreciate the help, what i'm missing here?
Thank you!
Use the email validation inside on onClick event like this and set the var allAreFilled false is email validation failed
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
});
/* Here email valdation */
const email = $('#email').val();
if( !email.match(
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
)){
allAreFilled = false;
}
/* terms and condtions check */
if( !$('#CartTermsDrawer').is(':checked') ){
allAreFilled = false;
}
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
return;
}
};

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

Validation gets removed after calling event.preventDefault()

Validation gets removed from SSN textbox after calling event.preventDefault(); in $("form").submit(function (event)
Validation gets fired and than removed
function CheckSSN() {
var sender = $("#SSN");
var value = $(sender).val();
var errorSpan = $(sender).siblings("span[data-valmsg-for='SSN']");
var message = "SSN is required.";
var validAliasPatt = /^[0-9]{9}$/;
if (!value || value == "" || value == null) {
enableValidationUI(sender, errorSpan, message);
return false;
}
else if (!validAliasPatt.test(value)) {
message = "SSN should be a 9 digit number.";
enableValidationUI(sender, errorSpan, message);
return false;
}
else {
disableValidationUI(sender, errorSpan);
return true;
}
}
----------
("form").submit(function (event) {
var submit = true;
if (!CheckSSN()) {
event.preventDefault();
var submit = false;
}
if (submit) {
$("form").submit();
}
else {
event.preventDefault();
return;
}
});
The issue was with using ("form").submit(function (event) which ended up creating endless loop. After changing to ('button').click fixed this issue.

Submitting canceling form submit from inside second function call

I'm trying to stop my form from submitting when the confirmation message is cancelled, but how can I cancel my form’s submission from inside the each()?
$('#myForm').submit(function() {
var inputs = $(this).find('input:checked');
inputs.each(function() {
var inputId = $(this).attr('id');
if(inputId != undefined && inputId.substring(0, 8) == 'inputName') {
var r = confirm("Are you sure you want to continue?");
if (r == true) {
return true;
} else {
// This doesn't stop the form submit
return false;
}
}
});
return true;
});
You can use the event argument that’s passed to event listeners instead; it has a method named preventDefault() that stops the default action from being performed.
$('#myForm').submit(function (e) {
var inputs = $(this).find('input:checked');
inputs.each(function () {
var inputId = this.id;
if (inputId != undefined && inputId.substring(0, 8) == 'inputName') {
var r = confirm("Are you sure you want to continue?");
if (!r) {
e.preventDefault();
}
}
});
});

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

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

Categories