dump jquery object in an alert box - javascript

I am not quite adept in maneuvering jQuery, and it came to a point that I need to debug a program that was passed down from me without a documentation.
I have this var a, an object, that I really want to know the content of its collection. In my mind I need a function like foreach() in PHP to iterate over this object variable. Upon researching I end up in using jQuery.each(). Now I can clearly iterate and see what was inside var a.
However, it was kind of annoying to alert once every value on the var a. What I wanna know if it's possible to display all the contents in just one pop of alert box?
Here is my code:
$.each(a, function(index, value) {
alert(index + ': ' + value);
});
The var a contains infos such as:
creationdate: date_here
id: SWFUpload
modificationdate: date_here
type: .jpg
index: 0
name: uploaded_filename.jpg
size: size_in_bytes
BTW: The var a is called via file upload script.

Why don't you just accumulate the values in an array, then display the whole array (for instance, using JSON)? Example:
var acc = []
$.each(a, function(index, value) {
acc.push(index + ': ' + value);
});
alert(JSON.stringify(acc));
In any case, I'd suggest using a debug tool like Firebug. So you could just use console.log(a) and be able to navigate freely through the objects's fields.

In firefox you could try:
alert(yourObject.toSource());
OR you could use some plugin:
See: jQuery Dump Plugin

Related

Passing a json array to javascript function in a jade rendered page

I have a json array being passed to a jade template.
This template then runs through the array adding rows to the html output.
However a new requirement no needs that json object to be passed to a javascript function, so I tried:
- var json = JSON.stringify(rows);
input.medium.success.button.error(type='submit', id='update_details', value= sendCommandLabel, onclick='sendCommand(' + json + ')')
which gives the following output (the full array omitted from brevity):
<input type="submit" id="update_details" value="Send Command" onclick="sendCommand([{"id":"id1;,"param1":value1, ... "}])">
Which is not useful as I am want to use this output in the javascript function and as it stands I can't consume it.
I am hoping I am missing something simple as my other option is to recreate the json array by looping through the objects in the renderer to recreate it!
UPDATE: I modified the code so instead of passing the array to the function, the array is hardcoded into the function while the jade page was being compiled. So this:
function sendStopCommandToAllSensors()
{
var hardcode = !{JSON.stringify(rows)};
became
function sendStopCommandToAllSensors()
{
var hardcode = [{"id":"id1", ... }, {"id":"id2", ... }];
But that still didn't work.
Puzzlingly adding a couple of simple alerts in there showed that there was the correct number of objects (later confirmed that there by cutting and pasting the resultant string directly into code and then manually adding a third object).
alert(hardcode.length); // displays 2
alert("rows: " + hardcode); // displays [object Object],[object Object]
Which is why in the loop that follows the
for (var row in hardcode)
{
alert("row: " + row); // displays 0 or 1, not an object
if (row.active == 1)
{
alert("Reached here"); // never reached
the final line is never reached.
UPDATE II: By stringifying hardcode I can output the human readable json.
alert("rows: " + JSON.stringify(hardcode));
Why is the code not seemingly parsing the array correctly and what to I do need to do correct it?
UPDATE III: I now having it working by using a two step traditional loop and assignment.
for (var i=0; i<rows.length; i++)
{
var row = rows[i];
So the question seems to be now, why didn't the for..in loop work as expected?
I am new to this, but I was going through similar problem I think.
But I am totally ok with JSON.stringify method, which was your first solution. It looks ugly in generated hmtl, but I found it useful in my case.
At least I think I understood it right and you are not trying to do some kind of magic what I can't absorb yet.
if
rows=[{id:id,param:param},{id:id2,param:param2}]
JADE:
- var json = JSON.stringify(rows);
input(type='submit', onclick='myFunction(' + json + ')')
JS:
function myFunction(myRows) {
console.log(myRows[0].id);
console.log(myRows[0].param);
console.log(myRows[1].id);
console.log(myRows[1].param);
.
.
at least it is ok in what I am working on.
I hope I didn't wrote pile of nonsense :)

Is it possible to find html attributes with specific start? (not specific value)

Imagine that you have the following button:
<button id="id" data-trigger-function = "true", data-value-1="12345", data-value-guid="534-534-657647365-gd">Click Me for Function</button>
Is it possible, to get something like the following in the called function:
$(this).attr('data-value-'+ * ).each(...);
The objective would be to use a universal selector in the attribute name, and not in the attribute value (not something like this: [name^='something']). The objective is to get the values of data-value-1 and data-value-guid because they both have the same start.., this means that data-value could be, data-value-qwerty, data-value-xpto, without having to know the *.
I've searched this, but couldn't find anything like this, or any mentions to something like this. Is it possible?
Thank you! (sorry for the bad english)
You could get all attributes and loop through them:
$.each(this.attributes, function(index, attr){
var name = attr.name;
if(name.startsWith('data-value') {
var value = attr.value;
//You code goes here
}
});
Another option:
You may also choose to iterate thru the data-* only and filter our the ones that start with value like below:
$.each($("button").data(), function(key, val) {
if (key.match(/^value/i)) {
alert (key + ": " + val);
}
})
Note: the above requires you to change data-value-1="12345" to something like data-value-one="12345"
A Demo

Jquery object is undefined after sort but is in firebug

I do an ajax call to a script that returns data. I see the data in firebug and it is correct. When the data comes back I do a sort and it works too. I see in firebug the object is sorted the way I want. After the sort I try to access a key/value pair. I see in firebug that the key/value I want is in the object. When I try to use the object key/value to assign to a var it is undefined. I'm trying to aggregate repeating data. If I'm not using the best way to do it, please help me with a better method.
data sample
coreDate "060115"
coreType "asterisk_11"
fileName "/var/www/html/Cores/gdb.hamid.asterisk.060115"
jid "hamid"
code
$.when (
$.ajax( {
type:"GET",
url: 'cf.php',
dataType: 'json',
timeout: 120000,
})
)
.done(function(coreInfo) {
coreInfo.sort(function(a,b) { return a.coreType > b.coreType } );
var coreStats={};
coreStats.numOfCores=0;
coreStats.numOfCoreType=0;
coreStats.prevCoreType=coreInfo.coreType;
// for some reason coreInfo.coreType is not defined. The coreInfo object exists and coreType is there. I tried this.coreType but is undefined.
$.each(coreInfo, function() {
coreStats.numOfCores++;
if (coreStats.prevCoreType != this.coreType) {
// This works. why do I have to access this.coreType instead of coreInfo.coreType?
$('#list > tbody:last-child').append('<tr><td><a href="'+this.fileName+'">'+this.coreType+'</td><td>'+coreStats.numOfCoreType+'<br>core</td><td>jid</td></tr>');
coreStats.numOfCoreType=0;
}
coreStats.numOfCoreType++;
coreStats.prevCoreType=this.coreType;
// setting prevCoreType works here
});
$('#cores').html("<h1>"+coreStats.numOfCores+"</h1><br>Core Files");
})
.fail(function() {
});
From your code and description, it sounds like coreInfo is an array of objects, is that right? If it were an object, it wouldn't have a sort() method and your code would stop right there.
If it's an array, it doesn't have a property like coreInfo.coreType. Each element of the array is an object with coreType and other properties. That's why you are able to access this.coreType inside the $.each() callback. $.each() iterates through the array, element by element, and passes each individual element into the callback.
Where it looks like you're seeing coreInfo.coreType in Firebug outside the $.each(), I suspect that what you're actually seeing is coreInfo[0].coreType, i.e. the first element of the array.
To help keep track of whether a variable is an array or not I strongly suggest giving arrays names that reflect this fact: either a plural word, or add List or Array to the name, or something. A name like coreInfo sounds like a singular item. I would call the array coreList, coreArray, or simply cores. Personally I like plural words for brevity: cores for the array of core info, core for an individual element in that array.
This way when you see cores.coreType or coreList.coreType or coreArray.coreType it will look wrong.
BTW for much more readable code, I suggest never using this in a $.each() callback. Instead, use named parameters.
$.each( coreInfo, function( i, core ) {
coreStats.numOfCores++;
if( coreStats.prevCoreType != core.coreType ) {
$('#list > tbody:last-child').append(
'<tr>' +
'<td>' +
'<a href="' + core.fileName + '">' +
core.coreType +
'</a>' + // MISSING IN ORIGINAL
'</td>' +
'<td>' +
coreStats.numOfCoreType +
'<br>core' +
'</td>' +
'<td>' +
'jid' +
'</td>' +
'</tr>'
);
coreStats.numOfCoreType = 0;
}
coreStats.numOfCoreType++;
coreStats.prevCoreType = this.coreType;
});
Note that there was a missing </a> in your markup in the code above. It's much easier to spot an error like this if you indent the markup strings in the same way that you might indent raw HTML code, instead of cramming it all onto one line.
A minor point: You don't need to wrap $.ajax() inside $.when(). $.ajax() returns a Promise that you can use directly.
You don't need the code that computes coreStats.numOfCores. You can simply use the length property of the array. If you follow my suggestion to call the array cores you could do this:
$('#cores').html( "<h1>" + cores.length + "</h1><br>Core Files" );
Finally, your sort callback function has a bug and will not sort the array properly. It may have worked in a simple test case, but it will fail to sort other arrays. It has to handle all three cases: <, ==, and > and return an appropriate value for each case, perhaps like this:
coreInfo.sort( function( a, b ) {
return(
a.coreType < b.coreType ? -1 :
a.coreType > b.coreType ? 1 :
0
);
});
To verify my assumptions, can you post an example of your actual JSON data, not a formatted table?

javascript use var value as name for new var

How can I use an array key (text value) to reference a variable by that same name?
jsFiddle
var cr,au,gen,bn,fmt,str;
var sbASCtrls = {"cr":"ContentRating","au":"Gold","gen":"Gender","bn":"Big Number","fmt":"Format","str":"Starting String"};
for (var key in sbASCtrls){
//This does not work ... breaks script
"'"+key+"'" = sbASCtrls[key];
alert('var CR: ' + cr);
return false;
}
In another language, I would simply surround the var name with percent signs, thus:
var %key% = "bob";
Would make:
var cr = bob;
How can this be done in javascript?
Why I require this unusual solution:
A series of AJAX calls are being made to a pre-existing PHP processor file that expects all data in HTML. In this case, I already had the data in JSON/jsObj format and wished to quickly break it out into separate variables. The most efficient/readable (believe it or not!) code was achieved by using eval(). After reading Jonathan's and Niet's posts/comments, I struggled with how to keep the data in JSON format and use it like that, but the AJAX processor always requires one piece of data in HTML format. To my disappointment, I was unable to find a way to mix the two data types. Faced with the choice of re-coding the entire app to use JSON only, or moving ahead with HTML, the SDLC made the decision for me.
Thanks Niet, Jonathan, Cristy, Stephen Thomas and Fallenreaper for sound advice and great ideas. I'll be scoping other posts you've each made.
While you could use eval like this:
// DO NOT DO THIS
eval(key+" = svASCtrls[key];");
You should probably stop and ask yourself why you want to do this in the first place. You already have a very tidy object, so just use it...
You can define your variables as properties of an object
var obj = { cr: null, au: null, gen: null, bn: null, fmt: null, str: null };
var sbASCtrls = {"cr":"ContentRating","au":"Gold","gen":"Gender","bn":"Big Number","fmt":"Format","str":"Starting String"};
for (var key in sbASCtrls){
//This does not work ... breaks script
obj[key] = sbASCtrls[key];
alert('var CR: ' + obj.cr);
return false;
}
As any global variable is a child of the window object, you can create the variable at window[key]
for (var key in sbASCtrls){
alert("key: " + key);
alert("val: " + sbASCtrls[key] );
//This should work, but jsfiddle messes with the window object
window[key] = sbASCtrls[key];
alert('var CR: ' + cr);
return false;
}
Note that this does not work on jsfiddle, but should work on your website.

Retrieving the last set of key values from array using JQuery

complete noob currently trying to complete a Uni assignment. We are creating a web app using HTML, css and JQuery. I've searched the web for an answer but can't quite figure out what I'm supposed to do.
I have set up a page where users can type in details for a shift, when they submit it, the data is pushed onto an array stored in localStorage using JSON stringify. That part works great and here it is:
var shift = {'location':$('#shift_location').val(), 'start_time':$('#shift_start_time').val(), 'end_time':$('#shift_end_time').val()};
var shift_list = JSON.parse(localStorage.shift);
shift_list.push(shift);
localStorage.shift = JSON.stringify(shift_list);
However I then need to take the last 'shift_location' 'shift_start_time' and 'shift_end_time' that has been added and stick it in a div on the page.
This is what I have come up with so far:
var result = JSON.parse(localStorage.shift);
$.each(result, function(k, v) {
$('.current_shift').text(k + ":" + v);
});
However, all that appears on the page is: 0:[object Object].
Any ideas on how to sort this out would be great. Like I said I'm a complete noob and this is my first time posting on here so apologies in advance if I've missed out any important bits of code or framed the question incorrectly.
Thanks
James
You have an array of objects, you have to get the last object in the array first :
var result = JSON.parse(localStorage.getItem('shift'));
var obj = result.pop();
$('.current_shift').text(obj.start_time + ":" + obj.end_time);
This is an Array shift_list.
So it looks like locationStorage.shift is an array. That is why the k is an integer. Try this:
$.each(result, function(k, v) {
$('.current_shift').text(v.location);
});
You will see that it is an object since your shift is stored in Objects. For debugging you can do this:
$.each(result, function(k, v) {
console.log(v);
$('.current_shift').text(v.location);
});
Open Chrome, and look at the console, there you will see your objects.

Categories

Resources