Wednesday, October 19, 2011

Recently learned Javascript (dynamic variables and jQuery objects vs. HTML DOM objects)

I recently learned two things in Javascript recently. Simple stuff really, but nobody told me and I didn't read it anywhere and had to go looking. Luckily I found some good references on stack overflow.

Dynamic variable names

Say for instance you generate some Javascript via your server side page language, whatever it may be:
var dynamic_1 = "1";
var dynamic_2 = "2";
Given these variables how to access them dynamically? I learned that you can access global variables like this via the window like this:
var get_dynamic_1 =  window["dynamic_" + "1"];
var get_dynamic_1 =  window["dynamic_" + "2"];
Now, of course, the string concatenation would be dynamic in a loop or something. I had to do it inside a change event call back function in jQuery:
$('input[name="formField"]').change(function(e){
   var localValue = window["dynamic_" + $(this).val()];
});
In this example, the variable is fetched using the form field value.

See also: Javascript dynamic variable name

jQuery objects verses HTML DOM objects

I was frustrated recently with jQuery when I was selecting a form object that I didn't have the same access to the HTML DOM object as I did in the jQuery object. I later found out that I did have access. For example:
var htmlDomFormObj = document.getElementById("user-input-form");
var jqueryObj = $("#user-input-form");
On the HTML DOM object I can do this:
htmlDomFormObj.formField.value = "something";
Then on the jQuery object, I thought I could only do this:
jqueryObj.children('input[name="formField"]').val("something");
It turns out, I can do the following:
jqueryObj[0].formField.value = "something";
The jQuery object provides access to the underlying HTML DOM object, the base object is simply wrapped.

See also: document.getElementById vs jQuery

No comments:

Share on Twitter