I've got a contact field on my website, and tests whether the value inserted is good or not. That part works fine. If a value is right, there is a var made with value = true.
I'm also calling a second function, which tests if all the contacts fields have got a true. If so, the send button will be abled, otherwise it keeps disabled. Sadly enough I get an error in my console, which says: Uncaught ReferenceError: nameIsGoed is not defined.
Hope you can help me out! :)
One of the tree functions which are quietly the same
function checkEmptyMessage(field) {
if (field.value != '') {
document.getElementById("message").style.borderColor="#91bc1e";
var messageIsGoed = true;
}
else if (field.value == ''){
document.getElementById("message").style.borderColor="#f15a24";
var messageIsGoed = false;
}}
The function that checks whether the value is true or not, if so: disable get's false.
function checkDisable(){
if ((nameIsGoed == true) && (messageIsGoed == true) && (mailIsGoed == true)){
document.getElementById("submit").disabled=false;
alert("mooizo");
}
else{
alert("er missen nog gegevens");
}
}
You have a scope problem, var messageIsGoed; should be (declared) outside your function, so the value you give it is available to other functions.
var messageIsGoed; // outside the function
function checkEmptyMessage(field) {
if (field.value != '') {
document.getElementById("message").style.borderColor="#91bc1e";
messageIsGoed = true;
}
else if (field.value == ''){
document.getElementById("message").style.borderColor="#f15a24";
messageIsGoed = false;
}}
I added (declared) var messageIsGoed; outside the function and removed the var inside the function so you don't declare it again (which actually makes a new variable only available inside that function).
Read more here about declaring variables: MDN:var
You cant use messageIsGoed outside of function if you declared it using var.
Just declare it outside both functions and use it inside without var so it will be global.
That's a local variable.
It only exists inside the function it's declared in.
You want to make a global variable, which will exist everywhere.
Declare the variable outside the function.
Related
Im trying to use global variables for my js and its like below code
var fullName = document.getElementById("elementId").value;
var nameFormat = /^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$/;
but when I try to use it inside a function function dosen't work .So I just pasted the var fullName into the function and then it works. So please tell me can I assign values into a global variable via document.getElementById("elementId").value;
When I try to use nameFormat inside function it works either declare inside or outside.
This is the full code
//common js regular expressions
var emailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var nameFormat = /^[A-Za-zÀ-ú]+ [A-Za-zÀ-ú]+$/;
//global variables
var fullName = document.getElementById("jsname").value;
var email = document.getElementById("jsun").value;
function validateForm() {
//var fullName = document.getElementById("jsname").value;
//onsubmit full name validation
if (!(fullName.match(nameFormat))) {
document.getElementById("pidnamevalidate").innerHTML = "Name should be in a valid format";
document.getElementById("pidnamevalidate").style.color = 'green';
return false;
//onsubmit email validation
} else {
return true;
}
}
It is fine for "nameFormat" to be a global variable, but it looks like you're getting fullName from an editable form field. If you set fullName outside of the validateForm function then you are setting it to the initial value of the field (or as #RobG mentioned, possibly trying to get the value of an element that doesn't yet exist in the DOM which would result in an error). Setting fullName inside validateForm will get its value at that point in time which I assume is what you want.
The following script works correctly although I need to make few amends. In each function I am getting the values need for the different formulas. However I tend to replicate the same line of code in different functions.
Ex.
function one(){ var v1= document.getElementById('one').value; }
function two(){ var v1= document.getElementById('one').value; }
Full code
I would like to declare all of the variables once and than only use the ones I need for the specific functions. If I declare them right at the top than once they are called they still hold the original value so I need to update that value to the current one if changed of course.
Your code will be very hard to read if you do it like in your fiddle.
Instead do
var myVars;
window.onload=function() {
myVars = {
'list_price': document.getElementById('list_price'),
'negotiated': document.getElementById('negotiated'),
.
.
'lease_payment': document.getElementById('lease_payment')
}
now you can do
var price = myVars.list_price.value;
or perhaps add a function
function getVal(id) {
var val = document.getElementById(id).value;
if (val =="" || isNaN(val)) return 0;
return parsetInt(val,10);
}
now you can do
var price = getVal("list_price");
mplungjan's solution is a great one. If you're at all concerned by your global vars leaking into the window scope, wrap your code in an Immediately Invoked Function Expression to prevent that from happening:
(function(){
// code goes here
}());
There are two ways to go about this:
Update your variable when the value changes
Use a function that always returns the correct value
1) You can add a listener for the change event or the keyup event that changes your global variable:
// save initial value
var val = document.getElementById('one').value;
// update the value when input is changed
addEventListener(document.getElementById('one'), 'change', function() {
val = document.getElementById('one').value;
});
console.log(val);
2) You can use a function that always returns the current value:
var val = function() { return document.getElementById('one').value; };
console.log(val());
2b) If you hate parenthesis, you can define a property that uses the function above as a getter:
Object.defineProperty(window, 'one', {
get : function() { return document.getElementById('one').value; }
});
console.log(one);
I am trying to create a generic click event function for all the fields on a page which primarily checks for the target being blank or containing a user-entered value. However, I would like for this generic function to check for existence of a more specific function and, if one is found, to allow it to handle the validation of the target value.
example:
function genValueCheck(event) {
var af = event.target.id+'_checkValue';
if (typeof af == 'function') runFunction(af,[event]); // logic specific to this field
else {
// logic for checking for blanks, etc which applies to all fields
}
}
However, typeof returns 'string' in the above example, as it should since it is checking for the typeof 'af', and not what 'af' contains, i.e. the name of a function.
Is what I am attempting to do possible?
Thanks in advance.
That's because af is a string. If your function exists in the global scope, use window[af]. This should work for you:
function genValueCheck(event) {
var af = event.target.id+'_checkValue';
if (typeof window[af] == 'function') runFunction(af,[event]); // logic specific to this field
else {
// logic for checking for blanks, etc which applies to all fields
}
}
Demo
Create an object that contains all your functions so you don't pollute the global namespace, then use bracket notation to retrieve it:
var validators = {};
validators.checker1 = function() { ... };
function genValueCheck(event) {
var af = event.target.id+'_checkValue';
if (typeof validators[af] == 'function') {
validators[af](event); // logic specific to this field
} else {
// logic for checking for blanks, etc which applies to all fields
}
}
Take a look at this:
if(session.getAttribute("mode")!=null){
mode = (String)session.getAttribute("mode");
}
The first time value for the mode is empty so I set the mode value to a script variable like this:
var mode='<%=mode%>';
below is the method in which I call on load of the form, but it says mode is undefined
bodyOnLoad();
var mode='<%=mode%>';
alert("mode : "+mode);
function bodyOnLoad() {
if(mode.length < 0){
alert("mode empty 111111");
document.getElementById("functiontype").value="view";
document.getElementById("page").value="1";
document.forms["frmTempcard"].submit();
return;
}
}
Can anyone help me with this?
Declare the variable first. The mode is undefined when you call the function bodyOnLoad.
var mode='<%=mode%>';
bodyOnLoad();
I load the same script in my page many times. I have some trouble on decide which is loaded first/after in my website, due to the async/load functions.
So, I'd like to put a global variable that count, when the script is loaded, the order of them.
So myScript.js will start with :
(function () {
var privateNumberScriptLoaded;
if (numberScriptLoaded === undefined) {
numberScriptLoaded = 0;
}
else {
numberScriptLoaded = numberScriptLoaded + 1;
}
privateNumberScriptLoaded = numberScriptLoaded;
console.log(privateNumberScriptLoaded);
})();
but when I load it with :
<script src="http://www.mywebsite.com/widget/myScript.js?type=normal" type="text/javascript"></script>
<script src="http://www.mywebsite.com/widget/myScript.js?type=rotation" type="text/javascript"></script>
I get (for two times) numberScriptLoaded is not defined.
How can I resolve this trouble? In fact I'll "create" a global variable in my website if it doesnt exist. Than increment it and store in a "private" variable for each script, so I can save the order of the execution for each script.
At present, your script falls prey to The Horror of Implicit Globals. I'd recommend not doing that.
You have three options:
As all global variables end up as properties on window, you could use window explicitly:
if (!window.numberScriptLoaded) {
window.numberScriptLoaded = 1; // 1, not 0
}
else {
++window.numberScriptLoaded;
}
Unlike the code without the window. prefix, that won't throw a ReferenceError, because looking up a property on an object works differently from resolving a freestanding identifier.
Live demo | demo page source | source of script it loads
Always put var numberScriptLoaded; (with no initializer) at global scope in your script, e.g. outside your scoping function:
var numberScriptLoaded; // No initializer (no = 0 or anything)
On the first load, this will create the variable; on subsequent loads, it's a no-op. Then you can do this without a ReferenceError:
if (!numberScriptLoaded) {
numberScriptLoaded = 1; // 1, not 0
}
else {
++numberScriptLoaded;
}
Live demo | demo page source | source of script it loads
Use typeof. If you take the typeof a variable that doesn't exist, you don't get a ReferenceError; you get "undefined". Then you can create it via the window. prefix (so you're not falling prey to The Horror).
if (typeof numberScriptLoaded === "undefined") {
// Assigning to window.numberScriptLoaded creates the global
window.numberScriptLoaded = 1; // 1, not 0
}
else {
++numberScriptLoaded;
}
Live demo | demo page source | source of script it loads
You should use typeof
if (typeof numberScriptLoaded === 'undefined') {
Try
if ( 'undefined' === typeof numberScriptLoaded ) {
numberScriptLoaded = 0;
} else {
numberScriptLoaded = numberScriptLoaded + 1;
}
myGlobalVar = typeof myGlobalVar == "undefined"? "New Value" : myGlobalVar;
myGlobalVar = typeof myGlobalVar == "undefined"? "Totally New Value" : myGlobalVar;
alert(myGlobalVar);
http://jsfiddle.net/8gnuwaah/2/
Global variables are direct attributes of window object. So if you'd like to init global variable from anywhere just type:
window.variableName = "what_ever_you_want"
As a best practice and to prevent this type of errors, all variables should be initialized before being used in your script.
You should put:
var numberScriptLoaded;
Just before your closure and the error won't happen.
If you're going to use the window to store the global, then you can do it in a single line with:
window.numberScriptLoaded = (window.numberScriptLoaded || 0) + 1