hello I would like my delivery variable created in the first function to be used in the second function
$('input[name="choix_livraison"]').on('click', function() {
var livraison = $(this).attr('data-nom')
console.log("verification si variable passe",livraison)
});
$("#cb_Nom").keyup(function() {
console.log("verification si variable passe",livraison)
});
var livrasion;
$('input[name="choix_livraison"]').on('click', function() {
livraison = $(this).attr('data-nom')
console.log("verification si variable passe",livraison)
});
$("#cb_Nom").keyup(function() {
console.log("verification si variable passe",livraison)
});
You can declare it as a global variable and since JQuery runs on the client side you don't have to worry about it being over written by other users.
Related
I need to change a global variable through a click event, but it seems (I suspect) that it won't change that variable value outside the event. i'm looking for making some calculations based on local variables from click events. When I declare it I get a message that local variables are not defined. It’s understandable because event hasn’t happened yet. Even after it does I can read updated values of local variables in browser console but global variable still remains undefined.
Here is some of the relevant code:
const tanqueSel = document.getElementById("tanqueSel"),
soldadoSel = document.getElementById("soldadoSel"),
guerreroSel = document.getElementById("guerreroSel"),
vikingoSel = document.getElementById("vikingoSel");
let Eleccion
tanqueSel.addEventListener("click", clickTanque)
function clickTanque() {
Eleccion = {
...tanque
};
alert("Has seleccionado " + Eleccion.nombre);
//I can access the new 'Eleccion' values here, but not outside
}
soldadoSel.addEventListener("click", clickSoldado)
function clickSoldado() {
Eleccion = {
...soldado
};
alert("Has seleccionado " + Eleccion.nombre);
}
guerreroSel.addEventListener("click", clickGuerrero)
function clickGuerrero() {
Eleccion = {
...guerrero
};
alert("Has seleccionado " + Eleccion.nombre);
}
vikingoSel.addEventListener("click", clickVikingo)
function clickVikingo() {
Eleccion = {
...vikingo
};
alert("Has seleccionado " + Eleccion.nombre);
}
let daño = (Eleccion.ataque - monstruo.defensa);
//According to the console this is where the problem is, since 'Eleccion' is undefined
It's a big antipattern to use global variables.
Also, the reason that you get undefined is because you're accessing that variable on the initial call stack of the application (that means that no click has happened yet, so yes, it is undefined).
I'm assuming that you are trying to calculate the 'damage' of an attack method.
When do you want to apply that damage? Shouldn't it be inside the click handler as well?
soldadoSel.addEventListener("click", clickSoldado)
function clickSoldado(){
// you can remove completely the global variable and use a generic function
attack(soldado);
}
//...same for every other click listener (you call attack method with the selection)
// and create a generic attack function
function attack(selected) {
alert("Has seleccionado " + selected.nombre);
let daño = selected.ataque - monstruo.defensa;
// here you have the damage, you can do what you want with it.
//...
}
I want to make the "var id" in the function global. That i can use the value of it in the alert outside the function. Thats my code:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
}
alert(id);
</script>
You didn't specified what is your final goal or why are you trying to move id to a global scope, but you can do it by simple moving the var id (declaration) outside the function, then it will be global and accessible by all functions.
Obviously, the alert will show "undefined" since id only gets some value when the myFunctionGetCode() is called.
The code below shows this.
var id;
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
id = con+code;
console.log(id)
}
alert(id);
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
BUT if you want to throw the alert with the id value only when it gets some value then you should move the alert() inside the function. (You can still declare the id variable outside the function to let it global, or inside the function, as you currently have)
Open snippet to see:
//var id; -> You can still declare it here (as global)
function myFunctionGetCode() {
var code = getInputVal('code');
var con = "/";
var id = con+code; //or you can declare it here, but not global
alert(id);
}
function getInputVal(elemId){
return document.getElementById(elemId).value;
}
<input id="code"/>
<button onclick="myFunctionGetCode()">Get Id</button>
From your sample code I guess that you do not want to make your value global, but that you want to return a value - after all you are doing an operation inside your function that calculates a value from certain inputs.
So you would use the return keyword, and call the function to get the value:
<script>
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
var id = con+code;
return id;
}
alert(myFunctionGetCode());
</script>
As a rule you do not want to make function variables global, since this means the value can be changed anywhere in your script or website, and that might lead to side effects and unexpected values in your function. If you need to pass something in use function parameters (or read from a text input like in your case), if you want to give back a result use return.
Can you move the alert inside the function or return the "id" value from the function instead?
You can make the variable global by doing something like:
window.your_namespace.id = value;
and then access the variable in the same way:
value = window.your_namespace.id
but its best not to pass data around using the global namespace.
You have to make var id to property of window object then you can access the id out side the function.
function myFunctionGetCode() {
var code = getInputVal('code'); //get value from Textinputfield from html
var con = "/";
window.id = 10;// Change to this
}
myFunctionGetCode();
alert(id);
I'm trying to avoid the use of global variables in my code, so I'm trying to use a work around by declaring them inside of $(document).ready and passing them as parameters to functions outside of $(document).ready, updating them, and then returning the updated value from those functions to manipulate the variables inside of $(document).ready.
Another way around this is to use hidden input fields to store variables but I also heard that was bad practice.
I'm wondering if I should just use global variables, do it the way I'm currently doing it, or use hidden input fields?
Below is a brief example of what I'm trying to accomplish. The variable validations is the variable I want to be able to use and update.
$(document).ready(function(){
var validations = [];
$('#inp').keypress(function(e){
if(e.which == 13){
e.preventDefault();
scanValidation(validations, function(valid){
validations = valid;
});
}
});
}):
function scanValidation(valid, cb){
var scanval = $('#inp').val();
if(valid.includes(scanval)){
//display error
}
else{
var validarr = valid.slice();
validarr.push(scanval);
var myData=JSON.stringify({ "name":"user1", "validations":validarr});
//Makes an ajax call to see if the sent array validarr is a valid request
apiCall(myData,'scanValidation',function(decoded) {
if (decoded.Status!="ERROR") {
valid = validarr;
}
else {
//display error
}
return(cb(valid));
});
}
}
Any variables declared within the immediately executed function below will NOT be in the global scope.
(function () {
var someVar = 'someValue';
$(document).ready(function() {
});
})();
Is it bad practice to instantiate variables inside of $(document).ready as opposed to globally declaring them?
No, not at all! Variables should always be declared in the scope they're needed in, nowhere else.
Another way around this is to use hidden input fields to store variables but I also heard that was bad practice.
I've never heard of that, but yes it definitely sounds like a bad practise. That's just the same as a global variable, but a global variable stored in the DOM for some odd reason.
I'm trying to avoid the use of global variables in my code, so I'm trying to use a work around by declaring them inside of $(document).ready and passing them as parameters to functions outside of $(document).ready, updating them, and then returning the updated value from those functions to manipulate the variables inside of $(document).ready.
That, admittedly, is a bit weird.
The easiest way to improve this is to move the function declaration inside the ready handler as well, and just access the variable there directly - with the additional bonus of not having a scanValidation global variable:
$(document).ready(function() {
var validations = [];
function scanValidation() {
var scanval = $('#inp').val();
if (validations.includes(scanval)) {
//display error
} else {
var validarr = validations.slice();
validarr.push(scanval);
var myData = JSON.stringify({"name": "user1", "validations": validarr});
// Makes an ajax call to see if the sent array validarr is a valid request
apiCall(myData, 'scanValidation', function(decoded) {
if (decoded.Status!="ERROR") {
validations = validarr;
} else {
//display error
}
});
}
}
$('#inp').keypress(function(e){
if(e.which == 13){
e.preventDefault();
scanValidation();
}
});
});
If you want to make scanValidation reusable, so that it could be called from other places as well with its own array, I would suggest to create a factory function that creates validators, each of which is a closure over its own array. That way, the array is declared where it belongs, so that the user of the function does not have to store the state for them:
function makeScanValidator(display) { // any other configuration
var validations = [];
// returns closure
return function scanValidation(scanval) { // take it as an argument
if (validations.includes(scanval)) {
display(/* error */);
} else {
var validarr = validations.concat([scanval]);
var myData = JSON.stringify({"name": "user1", "validations": validarr});
apiCall(myData, 'scanValidation', function(decoded) {
if (decoded.Status!="ERROR") {
validations = validarr;
} else {
display(/* error */);
}
});
}
}
$(document).ready(function() {
var validate = makeScanValidator(function display() { … });
$('#inp').keypress(function(e){
if(e.which == 13){
e.preventDefault();
validate(this.value);
}
});
});
var userIdD = $.get('http://someurl.com/options.php', function(abc) {
var abc = $(abc);
var link = $(abc).find('a:contains(View My Profile)');
//console.log (link);
var userID = $(link).attr('href');
var userId = $(userID);
console.log(userId);
console.log(userID);
});
console.log(userIdD);
console.log(userId);
I can`t start using variables "userIdD" & "userId" outside function "abc".
Inside it, it works greatly.
Can someone help me to use them outside it? where I'm wrong?
Declare your variables outside the function:
var userID, userId;
var userIdD = $.get('http://someurl.com/options.php', function(abc) {
var abc = $(abc)
var link = $(abc).find('a:contains(View My Profile)')
//console.log (link)
userID = $(link).attr('href');
userId = $(userID)
console.log(userId)
console.log(userID)
})
console.log(userIdD)
console.log(userId)
The problem is that userIdD is set asynchronously. The stuff that happens inside the function call happens after the stuff outside the function call.
Here's a simplified example which you can run:
$.get('http://jsonplaceholder.typicode.com', function(){
alert('Stuff inside function happening');
});
alert('Stuff outside function happening');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now, if we look at your code, we'll see that you're trying to console.log variables that are set inside the function call.
To go around the asynchronicity, you can make use of promises. Let's have a look at how that works...
var valuesPromise = $.get('http://jsonplaceholder.typicode.com').then(function(serverResponse){
return { objectId: 123 }; // return stuff you want to use later
});
// later in your code, you can make use of the returned value...
valuesPromise.then(function(returnedValue){
alert(returnedValue.objectId); // alerts '123'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am trying to get a variable from a javascript function, but I am having a problem getting it the variable value outside the function. The variable value can be outputted just fine inside the function. Here is the script, but how can I get the value of status and use it outside the funcion?
<script>
function get_id(){
$('.addressClick').click(function() {
var status = $(this).attr('id');
alert(status); // Here the value is printed correctly
return status;
});
}
var variable = get_id();
alert(variable); // Here the valiable isn't outputed
$("#"+variable).confirm();
</script>
You can't do this, see my example :
function get_id(){
$('.addressClick').click(function() {
//...
});
return 12;
}
var variable = get_id();
alert(variable); //12
'return status;' is in event function and not in get_id function.
The solution is that (don't use global variable if you have big project) :
$('.addressClick').click(function() {
$('.statusSelected').removeClass('statusSelected');
$(this).addClass('statusSelected');
});
alert($('.statusSelected').attr('id'));
$("#"+variable).confirm();