Variables with respect to DOM - javascript

This is surely a JS beginner question.
My issue is I want to use the value of the variable type to access the relevant checkbox; however it is treating the variable as a string. I have tried it to two ways.
function toggleGroup(type) {
if (document.getElementById(type).checked == true){
alert("foo");
}
}
or
function toggleGroup(type) {
if (document.nav.type.checked == true){
alert("foo");
}
}

We have no way of knowing how type should be treated - you haven't show us how the function is being called (in particular, we don't know what you are passing as its argument).
If it is a string (matching the id of an element), than document.getElementById(type).checked should work (although == true is redundant).
document.nav.type.checked should not work, because dot-notation property names are not interpolated. You have to use square bracket notation for that: document.forms.nav.elements[type].checked. This will match on name or id - if you have multiple elements with the same name, then document.forms.nav.elements[type] will be an object you can treat as an array (and won't have a checked property).

you can as well compare with "true"

Related

Javascript — objects containing functions with parameters

This is a fairly simple question, but I can't seem to find an example online. I've read up on objects and functions (i.e. here), but can't seem to find an example of a function within an object that accepts parameters.
In JavaScript, we can create an object, a nested object, and a method defined by a function:
var testObject = {
nestedObject : {
isNumber : function(number) { return !isNaN(number) };
}
}
How can I call my function with a specific parameter? Is the following correct?
testObject["nestedObject"].isNumber(number)
Thanks!
You kind of have the right idea but you need to refactor your object. This is how it would be written and called.
var testObject = {
nestedObject: {
isNumber :function(number) { return isNaN(number) }
}
}
then
testObject.nestedObject.isNumber(3);
Looks like there were just a few syntax errors in your code. Functions defined within an object behave the same way as regular functions defined outside of an object. The only difference is that you will have to use dot notation to access the functions on objects. So, try this code out:
testObject = {
nestedObject: {
isNumber: function(number) { return !isNaN(number) }
}
}
Now, you can call isNumber like this:
testObject.nestedObject.isNumber(4) // returns true
Note: Assuming you want your function isNumber to return true if the input is a number, we have to negate ( using ! ) the result of isNaN, as it returns true for values that are NaN.
Edit: When accessing properties (functions or otherwise) of an object, you can use dot notation as above, or you could use bracket notation, or some combination of the two. Here are a few examples:
testObject.nestedObject.isNumber(4) // dot notation
testObject['nestedObject']['isNumber'](4) // bracket notation
testObject['nestedObject'].isNumber(4) // combination of both
testObject.nestedObject['isNumber'](4) // alternative combination of both
There is not necessarily a right way to use bracket vs dot notation, but I think dot notation looks a little cleaner. I guess the only advice is to try to be consistent in however you decide to write it.
In this line:
testObject[nestedObject].isNumber(number)
nestedObject will be evaluated and its value will be passed as key of the property of testObject. What you need is to make it literal, to tell JavaScript that that is the property key.
Just to expand the information given by Tyler, these two are equivalents:
testObject["nestedObject"].isNumber(number)
And:
testObject.nestedObject.isNumber(number)

javascript 'short hand' notation in cycle plugin

I found this while going through some cycle plugin options:
$('#prev')[index == 0 ? 'hide' : 'show']()
I hate to admit but i'm having a hard time expanding this into it's 'long' form.
I know that if index is 0 element gets hidden otherwise it's visible.
It's the $('#prev')[index == 0 that is tripping me up :-(
Normally, you would write either $("#prev").hide() or $("#prev").show() depending on what you want to do.
However, you can access properties on objects by using square brackets [] with the property name as a string - among other things, this allows for object keys that contain characters that wouldn't be valid otherwise. Even something like obj["some property name"] would be valid here.
So basically, what your ternary operator is doing is choosing whether to get the show or hide string, which is then used to retrieve that property of the jQuery object (in this case, the methods) and calling them.
To make it simple for you, the code below:
$('#prev')[index == 0 ? 'hide' : 'show']();
is same as doing:
if (index == 0) {
$('#prev').hide();
} else {
$('#prev').show();
}
All that's really happening here is a test on the index variable. If it is equal to zero then the element is being hidden, otherwise it is being shown:
var elem = $('#prev');
if ( index == 0 ) {
elem.hide();
} else {
elem.show();
}
The 'hide' and 'show' strings are merely the names of the functions. Which function needs to be called is decided by the ternary conditional statement. Both of those functions are functions of the element and therefor you call them on the actual element. The brackets at the end of the statement is what actually calls the function.

Can you use a variable value to specify a jquery object name?

I have:
if (!myObj.login_id) {
alert("The object for login_id does not exist.");
} else {
alert("The object for login_id DOES exist. The value of the object is: " + myObj.login_id);
}
This is working properly. The object and it's value are defined already. However, I have multiple objects which are named after their ID attr. So, I try doing this (say for example this is a click event:
objtitle = $(this).attr('id'); // this is "login_id"
if (!myObj.objtitle) {
alert("The object for "+objtitle+" does not exist.");
} else {
alert("The object for "+objtitle+" DOES exist. The value of the object is: " + myObj.objtitle);
}
Why does it stop working when I use a variable for the name of the object?
Use square brackets.
myObj[objtitle]
There are two ways of accessing an object's properties: the dot syntax and the square bracket syntax. These are called member operators. So the following two are equivalent:
obj.foo
obj['foo']
The dot syntax (the first one) is a literal name. obj.objtitle therefore attempts to find a property called objtitle. If you have a variable containing the property name you want, you have to use the square bracket syntax.
myObj[objtitle]

Better Understanding Javascript by Examining jQuery Elements

Because jQuery is a widely used and mature collaborative effort, I can't help but to look at its source for guidance in writing better Javascript. I use the jQuery library all the time along with my PHP applications, but when I look under the hood of this rather sophisticated library I realize just how much I still don't understand about Javascript. Lo, I have a few questions for the SO community. First of all, consider the following code...
$('#element').attr('alt', 'Ivan is SUPER hungry! lolz');
vs
$('#element').attr({'alt': 'Ivan is an ugly monster! omfgz'});
Now, is this to say that the attr() method was designed to accept EITHER an attribute name, an attribute name and a value, or a pair-value map? Can someone give me a short explanation of what a map actually is and the important ways that it differs from an array in Javascript?
Moving on, the whole library is wrapped in this business...
(function(window, undefined) { /* jQuery */ })(window);
I get that the wrapped parentheses cause a behavior similar to body onLoad="function();", but what is this practice called and is it any different than using the onLoad event handler? Also, I can't make heads or tails of the (window) bit there at the end. What exactly is happening with the window object here?
Am I wrong in the assessment that objects are no different than functions in Javascript? Please correct me if I'm wrong on this but $() is the all encompassing jQuery object, but it looks just like a method. Here's another quick question with a code example...
$('#element').attr('alt', 'Adopt a Phantom Cougar from Your Local ASPCA');
... Should look something like this on the inside (maybe I'm wrong about this)...
function $(var element = null) {
if (element != null) {
function attr(var attribute = null, var value = null) {
/* stuff that does things */
}
}
}
Is this the standing procedure for defining objects and their child methods and properties in Javascript? Comparing Javascript to PHP, do you use a period . the same way you would use -> to retrieve a method from an object?
I apologize for this being a bit lengthy, but answers to these questions will reveal a great deal to me about jQuery and Javascript in general. Thanks!
1. Method overloading
$('#element').attr('alt', 'Ivan is SUPER hungry! lolz');
vs
$('#element').attr({'alt': 'Ivan is an ugly monster! omfgz'});
var attr = function (key, value) {
// is first argument an object / map ?
if (typeof key === "object") {
// for each key value pair
for (var k in key) {
// recursively call it.
attr(k, key[k]);
}
} else {
// do magic with key and value
}
}
2. Closures
(function(window, undefined) { /* jQuery */ })(window);
Is not used as an onload handler. It's simply creating new scope inside a function.
This means that var foo is a local variable rather then a global one. It's also creating a real undefined variable to use since Parameters that are not specified passes in undefined
This gaurds againts window.undefined = true which is valid / allowed.
the (window) bit there at the end. What exactly is happening with the window object here?
It's micro optimising window access by making it local. Local variable access is about 0.01% faster then global variable access
Am I wrong in the assessment that objects are no different than functions in Javascript?
Yes and no. All functions are objects. $() just returns a new jQuery object because internally it calls return new jQuery.fn.init();
3. Your snippet
function $(var element = null) {
Javascript does not support default parameter values or optional parameters. Standard practice to emulate this is as follows
function f(o) {
o != null || (o = "default");
}
Comparing Javascript to PHP, do you use a period . the same way you would use -> to retrieve a method from an object?
You can access properties on an object using foo.property or foo["property"] a property can be any type including functions / methods.
4. Miscellanous Questions hidden in your question
Can someone give me a short explanation of what a map actually is and the important ways that it differs from an array in Javascript?
An array is created using var a = [] it simply contains a list of key value pairs where all the keys are positive numbers. It also has all the Array methods. Arrays are also objects.
A map is just an object. An object is simply a bag of key value pairs. You assign some data under a key on the object. This data can be of any type.
For attr, if you give an object instead of a key value pair it will loop on each property.
Look for attr: in jQuery's code, then you'll see it use access. Then look for access: and you will see there is a check on the type of key if it is an object, start a loop.
The wrapping in a function, is to prevent all the code inside to be accessed from outside, and cause unwanted problems. The only parameters that are passed are window that allow to set globals and access the DOM. The undefined I guess it is to make the check on this special value quicker.
I read sometimes jQuery but I didn't start with it, may be you should get some good books to make you an idea first of what some advanced features Javascript has, and then apply your knowledge to the specifics of jQuery.
1 - Yes attr can accept a attribute name for getting a value, a name and a value for setting one value or a map of attribute names and values for settings more than one attribute
2 - A map is basically a JavaScript object e.g:
var map = {
'key1' : 'value1',
'key2' : 'value2'
};
3 - (function(window, undefined) { /* jQuery */ })(window); is something called an anonymous function as it doesn't have a name. In this case it also executes straight away.
A simple example would be:
function test(){
...
}
test();
//As an anonymous function it would be:
(function(){
...
}();
//And it you wanted to pass variables:
function test(abc){
...
}
test(abc);
//As an anonymous function it would be:
(function(abc){
...
}(abc);
this would make it different to the load event, as it is a function not an event.
4 - window is passed as a variable, as it is used internally within jQuery
5 - Objects and functions the same, as everything in JavaScript is an object. jQuery does something like this:
var obj = {
"init" : function(){
}
}
6 - Yes you can use . to retrieve a value on an object but you can also use [] e.g:
var map = {
"test" : 1
}
map.test //1
map["test"] //1
I hope this answers your many questions, let me know if I've missed anything out.
jQuery 1.6.1
The test is typeof key === "object"
if that is true, then you passed a { .... }
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},

Does Javascript have get/set keywords like C#?

I'm working with XULRunner and came across the following pattern in a code sample:
var StrangeSample = {
backingStore : "",
get foo() { return this.backingStore + " "; },
set foo(val) { this.backingStore = val; },
func: function(someParam) { return this.foo + someParam; }
};
StrangeSample.foo = "rabbit";
alert(StrangeSample.func("bear"));
This results in "rabbit bear" being alerted.
I've never seen this get/set pattern used in Javascript before. It works, but I can't find any documentation/reference for it. Is this something peculiar to XUL, a recent language feature, or just something I missed? I'm puzzled because I was specifically looking for something like this a few months ago and couldn't find anything.
For reference, removing "get" or "set" results in a syntax error. Renaming them to anything else is a syntax error. They really do seem to be keywords.
Can anyone shed some light on this for me, or point me towards a reference?
As suggested by Martinho, here are some links explaining the getter/setters in JS 1.5:
http://ejohn.org/blog/javascript-getters-and-setters/
http://ajaxian.com/archives/getters-and-setters-in-javascript
Be aware though, they don't seem to be supported in IE, and some developers have (legitimate) concerns about the idea of variable assignment having side-effects.
get/set are not reserved keywords as Daniel points out. I had no problem creating a top-level functions called "get" and "set" and using the alongside the code-sample posted above. So I assume that the parser is smart enough to allow this. In fact, even the following seems to be legitimate (if confusing):
var Sample = {
bs : "",
get get() { return this.bs; },
set get(val) { this.bs = val; }
}
According to Mozilla, they are not in ECMAScript.
JavaScript Setters And Getters:
Usually the setter and getter methods follow the following syntax in JavaScript objects. An object is created with multiple properties. The setter method has one argument, while the getter method has no arguments. Both are functions.
For a given property that is already created within the object, the set method is typically an if/else statement that validates the input for any time that property is directly accessed and assigned later on via code, a.k.a. "set". This is often done by using an if (typeof [arg] === 'certain type of value, such as: number, string, or boolean') statement, then the code block usually assigns the this.(specific)property-name to the argument. (Occasionally with a message logging to the console.) But it doesn't need to return anything; it simply is setting the this.specific-property to evaluate to the argument. The else statement, however, almost always has a (error) message log to the console that prompts the user to enter a different value for the property's key-value that meets the if condition.
The getter method is the opposite, basically. It sets up a function, without any arguments, to "get", i.e. return a(nother) value/property when you call the specific-property that you just set. It "gets" you something different than what you would normally get in response to calling that object property.
The value of setters and getters can be easily seen for property key-values that you don't want to be able to be directly modified, unless certain conditions are met. For properties of this type, use the underscore to proceed the property name, and use a getter to allow you to be able to call the property without the underscore. Then use a setter to define the conditions by which the property's key-value can be accessed and assigned, a.k.a. "set". For example, I will include two basic setters and getters for this object's properties. Note: I use a constant variable because objects remain mutable (after creation).
const person = {
_name: 'Sean';
_age: 27;
set age(ageIn) {
if (typeof ageIn === 'number') {
this._age = ageIn;
}
else {
console.log(`${ageIn} is invalid for the age's key-value. Change ${ageIn} to/into a Number.`);
return 'Invalid Input.';
}
},
get age() {
return this._age;
},
set name(nameIn) {
if (typeof nameIn === 'string') {
this._name = nameIn;
} else {
console.log(`Change ${nameIn} to/into a(ny) String for the name's
key-value.`);
return 'Invalid Input.';
}
},
get name() {
return this._name;
}
};
Where it gets interesting is when you try to set/assign a new key-value for the _age property, because it has to meet the if conditional in order to be successfully assigned, meaning not all assignments are valid, etc.
person.age = 'twenty-eight'; /* output: twenty-eight is invalid for the
age's key-value. Change twenty-eight to/into a Number. */
console.log(person.age); // output: 27 (twenty-eight was never assigned)
person.age = 28; // output: none
console.log(person.age); // output: 28
Note how I was able to access the person._age property via the person.age property thanks to the getter method. Also, similar to how input for age was restricted to numbers, input for the name property is now restricted/set to strings only.
Hope this helps clear things up!
Additionally, some links for more:
https://johnresig.com/blog/javascript-getters-and-setters/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
https://www.infragistics.com/community/blogs/infragistics/archive/2017/09/19/easy-javascript-part-8-what-are-getters-and-setters.aspx

Categories