make variable available in other function - javascript

I have a function
function formSubmitListener() {
$(".js-form").submit(event => {
event.preventDefault();
let input = fetchInput();
validateInput(input);
if (isValid) {
serverCall()
}
});
}
validateInput returns a isValid boolean of true (if all fields on a form have been filled out) that I need to make available for the if statement. If at all possible I want to prevent the use of a global variable.
How do I make the boolean available ?

function formSubmitListener() {
$(".js-form").submit(event => {
event.preventDefault();
let input = fetchInput();
let isValid = validateInput(input);
if (isValid == true) {
serverCall()
}
});
}
this might be what you want. set the validateInput(input) function call to a variable and use that variable since it will store the true/false.
or another way by putting the direct function in the if where it checks whats returned
function formSubmitListener() {
$(".js-form").submit(event => {
event.preventDefault();
let input = fetchInput();
if (validateInput(input)) {
serverCall()
}
});
}

Related

Next Js Router beforePopState , access state of component in handler

I am using Next js Router.beforePopState event and i want to access value of useState variable which i created in react component in which this handler is defined, sample code below , but whenever i access the state it is empty or set to default value for example in below code goaway state value i always get in handler as empty string "" even though i have set in code a different value, is there a way i can get the state value in handler?
const [goAway, setGoAway] = useState("");
const browserTabcloseHandler = e => {
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = "";
};
useEffect(() => {
if (window) {
Router.beforePopState(() => {
//if (componentShouldBeSavedAsDraft(componentData)) {
const result = window.confirm("are you sure you want to leave?");
if (!result) {
window.history.pushState("/", "");
Router.push("/marketplace/upload-component");
}
console.log(goAway); // this value is always "" even though set differently in code.
return result;
});
window.onbeforeunload = browserTabcloseHandler;
}
//Router.events.on("routeChangeStart", handleRouteChange);
return () => {
if (window) {
window.onbeforeunload = null;
}
Router.beforePopState(() => {
return true;
});
};
}, []);
i was able to find solution for same what i was missing is adding property in useEffect below code fixed the issue-
const [goAway, setGoAway] = useState("");
const browserTabcloseHandler = e => {
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = "";
};
useEffect(() => {
if (window) {
Router.beforePopState(() => {
//if (componentShouldBeSavedAsDraft(componentData)) {
const result = window.confirm("are you sure you want to leave?");
if (!result) {
window.history.pushState("/", "");
Router.push("/marketplace/upload-component");
}
console.log(goAway); // this value is always "" even though set differently in code.
return result;
});
window.onbeforeunload = browserTabcloseHandler;
}
//Router.events.on("routeChangeStart", handleRouteChange);
return () => {
if (window) {
window.onbeforeunload = null;
}
Router.beforePopState(() => {
return true;
});
};
}, [goAway]); // this fixed the issue

Target Variable from Variable Value

I am trying to target a variable from a variable value that has been passed in from function arguments. I don't know how to do this. P.S. the variables at the top are also used by other functions
let cardvalue0 = false;
let cardvalue1 = false;
function myfunction (card) {
if (card === false) {
card = true;
//ether cardValue 0 or 1 should now be true
return card;
}
}
// exturnal html
<button onclick="myfunction("cardValue0")"></button>
<button onclick="myfunction("cardValue1")"></button>
new try by me
//define cards
let card0State = false;
let card1State = false;
//toggle card status (read or not)
function cardToggle(card) {
console.log(card);
card = !card
console.log(card);
return card;
}
// external html
<button onclick="myfunction(cardValue0)"></button>
<button onclick="myfunction(cardValue1)"></button>
target a variable from a variable value? If I understood you right you want to access a variable cardvalue0 inside the function myfunction.
You can access it using, eval(card) but definitely not advised to do
function myfunction (card) {
if (eval(card) === false) { //this will work
card = true; //however you cannot change the original value
return card;
}
}
You can get this by using objects
let cardDict = { "cardvalue0" : false,
"cardvalue1" : false}
function myfunction (card) {
if (cardDict[card] === false) {
cardDict[card] = true;
return cardDict[card];
}
}
Would it be possible to store card0State and card1State in an object instead? Then you could reference them as keys to the object instead.
const cardvalues = {};
cardvalues.cardvalue0 = false;
cardvalues.cardvalue1 = false;
function myfunction (cardNumber) {
if (cardvalues[cardNumber] === false) {
cardvalues[cardNumber] = true;
//ether cardValue 0 or 1 should now be true
return cardvalues[cardNumber];
}
}
// exturnal html
<button onclick="myfunction('cardvalue0')"></button>
<button onclick="myfunction('cardvalue1')"></button>
Then you aren't declaring a new variable in the function scope and you are directly altering the key values on the object. This is usually better than a variable variable pattern.
"Variable" variables in Javascript?
the simpler would be moving the original variable (cardvalue0 and cardvalue1) in a Map or an object, so you could have :
cards = {
cardvalue0 : false,
cardvalue1 : false
}
function foo(cardName) {
cards[cardName] = !cards[cardName];
return cards[cardName]
}
}
if you can not move cardvalue0 and cardvalue1, you could simply hardcode them, but it will become ugly really fast.
function foo(cardName) {
if(cardName === "cardvalue0") {
cardValue0 = !cardValue0;
return cardValue0;
} else if(cardName === "cardvalue1")
cardValue1 = !cardValue1;
return !cardValue1;
}
eval would be the only way to get a variable from a string representation, but is not a good idea.

Vee-Validate validateAll() with scope

I have a scenario where I have sectioned out (scoped) a form so that I can validate small chunks at a time using the following function.
validateScope (scope) {
return this.$validator.validateAll(scope);
}
I want to do one final validation of the entire form before I submit it to the server; however, validateAll() doesn't seem to pick up inputs that have been added to a scope. I've also tried just validating each scope and then submit the form if they are ALL valid, but I am not sure how to do that since everything is asynchronous.
validateAll () {
let valid = true;
// Not sure how to build this function since validateScope is asynchronous
_.each(this.names, (name, index) => {
if (this.validateScope(`name-${index}`)) {
valid = false;
}
});
return valid; // Always returns true even though the _.each should set it to false
}
As mentioned in my comment, your code will end up looking something like this:
validateAll () {
let valid = true;
let validations = []
_.each(this.names, (name, index) => {
validations.push(this.validateScope('name-' + index))
});
return Promise.all(validations)
// consolidate the results into one Boolean
.then(results => results.every(r => r))
}
Then, of course, you'll have to use validateAll as a promise:
this.validateAll().then(isValid => {
if (!isValid) {
//do whatever you need to do when something failed validation
} else {
// do whatever you need to do when everything is valid here
}
})

how use javascript variable value to trigger an action

I need to use the value of a boolean variable to trigger an action, and I will use this in several occasions, then is very important I do in the best way.
I already search and found a way to use object.watch, like this:
let test1 = {on: false};
teste1.watch('on', function (prop, oldval, newval) {
if (teste1.on === true) {
$('#bot').toggleClass('switch-bck');
} else {
$('#bot').toggleClass('switch');
}
return newval;
});
interact('#bot2')
.on('down', function (event) {
event.currentTarget.classList.toggle('switch');
event.preventDefault();
if (teste1.on) {
teste1.on = false;
} else {
teste1.on = true;
}
document.getElementById('demo').innerHTML = teste1.on;
})
.on('up', function (event) {
event.currentTarget.classList.toggle('switch');
event.preventDefault();
document.getElementById('demo').innerHTML = teste1.on;
});
document.getElementById('demo').innerHTML = teste1.on;
This almost works.
When I change the state of teste1.on the first 2 times works well. But after this take the double of changes of teste1.on for the
$('#bot').toggleClass('switch-bck');
be activated. But I see that teste1.on change correctly because I see its value with
document.getElementById('demo').innerHTML = teste1.on;
If I change return newval to return oldval or even remove it, the change that I want happens perfectly, but the value that I se with
document.getElementById('demo').innerHTML = teste1.on;
remain freeze or show "undefined".
Any help? Or even a way to do this without using .watch?

Return from inner function in JavaScript?

I have a jQuery-powered JavaScript function which iterates over a list of fields and checks to see whether they are empty; if so, blocks the submission of the form.
required_fields.forEach(function(field) {
if (field.val() == '')
{
field.addClass('field-highlight');
return false;
}
else
{
field.removeClass('field-highlight');
}
});
// I want to return to here from the return false point
How can I structure this differently to do what I want?
Just use a variable to keep track of the validation:
var is_valid = true;
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
is_valid = false;
return false;
} else {
field.removeClass('field-highlight');
}
});
return is_valid;
Or, you can just use the field-highlight class as well:
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
return false;
} else {
field.removeClass('field-highlight');
}
});
return $('.field-highlight').length == 0;
use a boolean in the forEach closure, which would be set to true, if the field value is empty. Check that value before submission of form
It sounds like you want to do the following
Update the elements with the field-highlight class based on whether or not they have a value
Block the form submission if any are empty
If so then try the following
var anyEmpty = false;
required_fields.forEach(function() {
if ($(this).value() == '') {
$(this).addClass('field-highlight');
anyEmpty = true;
} else {
$(this).removeClass('field-highlight');
}
});
if (anyEmpty) {
// Block the form
}
Did you write the "forEach" function? If so, that could check the return value of the anon function, and if it is ever false, stop iterating.
If your required_fields is a jQuery object, you could just do this:
var stop = required_fields.removeClass('field-highlight')
.filter("[value == '']").addClass('field-highlight')
.length;
return !!stop
Or perhaps more efficient like this?
var stop = required_fields.filter('.field-highlight').removeClass('field-highlight')
.end().filter("[value == '']").addClass('field-highlight')
.length;
return !!stop

Categories

Resources