Skip to content Skip to sidebar Skip to footer

Is It Possible To Give A Variable A Default Value

Is it possible to give variables a default value if theyre not defined onload? I have variables in my script which need multiplying, only they take the value from input fields so o

Solution 1:

Do something like this

var conMin = document.getElementById('cMin').value || 'cMin_default'; 
var serLev = document.getElementById('sLev').value || 'sLev_default';

The variable will be assigned the value on the right if the value on the left is false, 0, "", null, or undefined.

Solution 2:

if (typeof someVar === "undefined") {
    someVar = 'a default';
}  

Solution 3:

You can try a couple of things.

As has already been suggested, you can populate the input fields with default values as one possibility.

As another, rather than pull the values straight from the input fields, do some validation as you bring them in and store them in variables (i.e. variables as in var variables, not variables as in those in the document). This will give you a chance to check to see if the value is appropriate and if it's blank, fill in a default, like so:

var conMin = '2'; //or whatever default value you wantif (document.getElementByID('cMin').value != '') {
    conMin = document.getElementByID('cMin').value;
}

Post a Comment for "Is It Possible To Give A Variable A Default Value"