Jonathan
Jonathan

Reputation: 1467

Printing out a javascript variable (not showing up?)

I want to make sure a javascript variable is getting the correct values passed into it when setting it to a ruby variable.

<script type="text/javascript" charset="utf-8">

   var test = <%= @test || 'null' %>;
   document.write(test);

</script>

However, there doesn't seem to be any output whatsoever. I've tried just document.write("somethinganything") and I still don't see any output. Is it supposed to appear on webpage or terminal? I couldn't find any in both.

Upvotes: 1

Views: 15018

Answers (3)

Steven Moseley
Steven Moseley

Reputation: 16325

You shouldn't use document.write() to print out visible content unless the script block is in the <body>.

Some older browsers will not support that, and if the script block is in the <head> it will not write anything visible.

Try one of the following solutions instead:

// Append a text node to the end of your body
window.onload = function() {
    var txt = document.createTextNode(test);
    document.body.appendChild(txt); 
};

or

// Log the text to your javascript console
console.log(test);

or

// Alert the text in a popup
window.alert(test);

Upvotes: 3

cruxi
cruxi

Reputation: 829

you have to write console.log("test");

Upvotes: 1

dsgriffin
dsgriffin

Reputation: 68586

document.write prints to the webpage. You should try using console.log to print to the terminal.

Upvotes: 6

Related Questions