Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I view an object with an alert()

I tried to do a debug but I am having problems. Now I try with alert(). For example I want to see the value of:

var product = { ProductName: $('!Answer_Response[0]').val(),
                  UnitPrice: $('#Price').val(),
                  Stock: $('#Stock').val()
              };

When I say alert(product) it just gives me [object Object]. How can I make alert show what's really there?

like image 679
Melova1985 Avatar asked Apr 22 '11 09:04

Melova1985


People also ask

How do you display an object in alert?

Using Window. alert() method displays a dialog with the specified content. Printing an object using the Window. alert() method will display [object Object] as the output. To get the proper string representation of the object, the idea is to convert the object into a string first using the JSON.

Which object contains the alert () method?

The alert() is a method of the window object.

What is the use of alert () function?

One useful function that's native to JavaScript is the alert() function. This function will display text in a dialog box that pops up on the screen. Before this function can work, we must first call the showAlert() function. JavaScript functions are called in response to events.

How do I see objects in console?

Answer: Use console. log() or JSON. stringify() Method You can use the console. log() method, if you simply wants to know what's inside an object for debugging purpose. This method will print the object in browser console.


3 Answers

you can use the JSON.stringify() method found in modern browsers and provided by json2.js.

var myObj = {"myProp":"Hello"}; alert (JSON.stringify(myObj));    // alerts {"myProp":"Hello"}; 

or

also check this library : http://devpro.it/JSON/files/JSON-js.html

like image 105
Pranay Rana Avatar answered Sep 20 '22 13:09

Pranay Rana


you can use toSource method like this

alert(product.toSource()); 
like image 26
aya Avatar answered Sep 20 '22 13:09

aya


If you want to easily view the contents of objects while debugging, install a tool like Firebug and use console.log:

console.log(product);

If you want to view the properties of the object itself, don't alert the object, but its properties:

alert(product.ProductName);
alert(product.UnitPrice);
// etc... (or combine them)

As said, if you really want to boost your JavaScript debugging, use Firefox with the Firebug addon. You will wonder how you ever debugged your code before.

like image 39
Aron Rotteveel Avatar answered Sep 20 '22 13:09

Aron Rotteveel