user31782
user31782

Reputation: 7589

How to add text in document.write() function when used with onclick event?

In the following code document.write() function is not able to take string as its argument,

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html> 

The problem seems to be that there are already quotations around "document.write(5 + 6)".

So how do I add a usual text string to it?

Upvotes: 1

Views: 5487

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386560

You may better use document.getElementById, because document.write is bad practice.

<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<p id="result"></p>
<button onclick="document.getElementById('result').innerHTML=5 + 6">Click Me!</button>

Upvotes: 3

smraj
smraj

Reputation: 152

Try this..

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick='document.write(5 + 6)'>Try it</button>

</body>
</html> 

Upvotes: 0

Lingaraju E V
Lingaraju E V

Reputation: 503

you can do this - let the string be in single quotes.

onclick="document.write('5 + 6')"

Note: You can interchnage single and double quotes. This also works

onclick='document.write("5 + 6")'

Upvotes: 1

Mani
Mani

Reputation: 949

Try with single quotes for string as below:

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write('Hello world')">Try it</button>

</body>
</html>

Upvotes: 3

Related Questions