getting variable/object elements and values in javascript - javascript

I'm not sure if I'm using the correct terminology, so please correct me if I'm not.
I've got a javascript variable which holds a group of values like this
var my_variables = {
first_var: 'starting',
second_var: 2,
third_var: 'continue',
forth_var: 'end'
}
Now I'm trying to get these variables in my script, but I don't want to have to check for each one.
Right now i'm doing this
if(my_variables.first_var!=null){
query=query+'&first_var='+my_variables.first_var;
}
if(my_variables.second_var!=null){
query=query+'&second_var='+my_variables.second_var;
}...
I'm hoping there is a simple way to recursively go through the object, but I haven't been able to find how to do that.
Something like
foreach(my_variables.??? as varName){
query=query+'&'+varName+'='+my_variables.varName;
}

Try this:
for(var key in my_variables)
query += '&'+key+'='+encodeURIComponent(my_variables[key]);

for (var varName in my_variables) {
query=query+'&'+varName+'='+my_variables[varName];
}
for (... in ...) is how you write this kind of loop in Javascript. Also use square brackets instead of a period when the field name is a value instead of the actual identifier, like here. Incidentally, I'd also suggest using window.encodeURIComponent if your values might contain arbitrary text.

Related

javascript regex match not working as expected

I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.
Part 1:
In the following example, I want to extract the part of the string between geotech and Input.
x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)
The result:
["geotechCITYInput", "CITY"]
I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.
Part 2:
The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.
Example form definition:
obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"
I ultimately want an array like this:
["CITY","STATE"]
I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.
geotechForm.forEachItem(function(name) {
if(name.match(/Input$/)
inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});
Any suggestions would be greatly appreciated.
You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.
geotechForm.forEachItem(function (name) {
var match = name.match(/^geotech(.*)(Input|List)$/);
if (match) {
inputFieldNames.push(match[1]);
}
});

Accessing a Dynamically Named Object Property

I'm creating a javavascript object which I'm calling rulesObject. The idea is for it to be a javascript object containing all of the rules I need to check to enable/disable other checkboxes that is dynamically generated from a mysql database at the very beginning of the script. For now, I'm just testing it out with two rules which I know create the scenario I'm looking for, so here's what my object looks like at the moment:
rulesObject = {
chk533570 : ["533577", "503671", "503667", "604028", "503661"],
chk503928 : ["533577", "533578","503671", "503666", "533576", "503667", "324201", "503221", "604028", "503668", "533580", "503669", "533579", "533581", "503670"]
};
Now what I need to do is access the information out of that object. If I do a simple alert(rulesObject. chk533570), it works PERFECTLY – gives me exactly what I need. However, what I'm going to need to do is access a specific rule based on what was just clicked by running through the following. So, for example, if I clicked the checkbox valued "533570", it would go through the following:
$('input').click(function(){
if(this.checked) {
checkRules(this.value, 'checked');
} else {
checkRules(this.value, 'unchecked');
}
});
(Of course I'm using jQuery there, but I'm using it throughout the web app so I don't mind going back and forth.)
Now onto my checkRules function. It's still very simple as it's in the beginning stages – I just want to alert the value of what I just selected. Again, if I do alert(rulesObject. chk533570), even within the function, I get the right result, but I need to access what I just selected, so I have to add the letters 'chk' to the beginning of the object property name and then append the justselected value (which in this case equals 533570). Here are the ways I've tried to do it:
function checkRules(justselected, state) {
rulename= 'chk' + justselected;
currentrules = rulesObject.rulename;
alert(rulename);
alert(currentrules);
}
Alert 1: chk533570
Alert 2: undefined
function checkRules(justselected, state) {
rulename= 'chk' + justselected;
alert(rulesObject.rulename);
}
Alert: Undefined
function checkRules(justselected, state) {
rulename= 'chk' + justselected;
alert(rulesObject + '.chk' + justselected);
}
Alert: [object Object].chk533570
function checkRules(justselected, state) {
alert(rulesObject.chk533570);
}
Alert: 533577,503671,503667,604028,503661
So, any idea how to properly call that name so that I get the right results? I also tried not having the 'chk' in there at all, but the javascript object didn't like a completely numeral property.
obj.key is the same as obj['key'] - but in the second way the key can be dynamic since it's a plain JavaScript expression.
So you can simply use rulesObject['chk' + justselected]:
function checkRules(justselected, state) {
alert(rulesObject['chk' + justselected]);
}
Long time ago people used to use alert(eval('rulesObject.chk' + justselected)); by the way. While this works, do not use this. Using eval() should be avoided at all times; and in this case there is a much cleaner way anyway.

Trying to reduce repetition of javascript using a variable

I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.

JavaScript/JQuery: use $(this) in a variable-name

I'm writing a jquery-plugin, that changes a css-value of certain elements on certain user-actions.
On other actions the css-value should be reseted to their initial value.
As I found no way to get the initial css-values back, I just created an array that stores all initial values in the beginning.
I did this with:
var initialCSSValue = new Array()
quite in the beginning of my plugin and later, in some kind of setup-loop where all my elements get accessed I used
initialCSSValue[$(this)] = parseInt($(this).css('<CSS-attribute>'));
This works very fine in Firefox.
However, I just found out, that IE (even v8) has problems with accessing the certain value again using
initialCSSValue[$(this)]
somewhere else in the code. I think this is due to the fact, that I use an object ($(this)) as a variable-name.
Is there a way arround this problem?
Thank you
Use $(this).data()
At first I was going to suggest using a combination of the ID and the attribute name, but every object might not have an ID. Instead, use the jQuery Data functions to attach the information directly to the element for easy, unique, access.
Do something like this (Where <CSS-attribute> is replaced with the css attribute name):
$(this).data('initial-<CSS-attribute>', parseInt( $(this).css('<CSS-attribute>') ) );
Then you can access it again like this:
$(this).data('initial-<CSS-attribute>');
Alternate way using data:
In your plugin, you could make a little helper function like this, if you wanted to avoid too much data usage:
var saveCSS = function (el, css_attribute ) {
var data = $(el).data('initial-css');
if(!data) data = {};
data[css_attribute] = $(el).css(css_attribute);
$(el).data('initial-css', data);
}
var readCSS = function (el, css_attribute) {
var data = $(el).data('initial-css');
if(data && data[css_attribute])
return data[css_attribute];
else
return "";
}
Indexing an array with a jQuery object seems fishy. I'd use the ID of the object to key the array.
initialCSSValue[$(this).attr("id")] = parseInt...
Oh please, don't do that... :)
Write some CSS and use the addClass and removeClass - it leaves the styles untouched afterwards.
if anybody wants to see the plugin in action, see it here:
http://www.sj-wien.at/leopoldstadt/zeug/marcel/slidlabel/jsproblem.html

How to access JSON.parsed object in javascript

I did JSON.parse and getting output in javascript variable "temp" in format like this
{"2222":{"MId":106607,
"Title":"VIDEOCON Semi Automatic Marine 6.8kg",
"Name":"washma01",
}}
I tried like
alert(temp[0][0]);
alert(temp.2222[0].MId);
but not getting output.
How will I access this data in javascript ?
alert(temp["2222"].MId);
You can't use numeric indexing, because don't have any actual arrays. You can use dot syntax if the first character of the key is non-numeric. E.g.:
var temp = JSON.parse('{"n2222":{"MId":106607, "Title":"VIDEOCON Semi Automatic Marine 6.8kg", "Name":"washma01", }}');
alert(temp.n2222.MId);
Try this:
temp["2222"].MId
Typically temp.bar and temp["bar"] are equivalent JavaScript statements, but in this case one of your property name starts with a number. When this happens you are forced to use the index (aka bracket) notation.
You need to access the variable like so temp['2222']['MId'] , That will give you the value of MId. Even though I have shown using the [] method of getting the value , the answers below work as well.
You can run this test below in firebug.
var ss = {"2222":{"MId":106607, "Title":"VIDEOCON Semi Automatic Marine 6.8kg", "Name":"washma01"}};
console.log(ss['2222']['MId']);
when you have a good json formated object, but you don't know the key (here it look like an id) you can acces like this :
var keys = Object.keys(json_obj);
for (var i = 0; i < keys.length; i++) {
console.log(keys[i]);
console.log(json_obj[keys[i]].MId);
};

Categories