user3481992
user3481992

Reputation: 33

making the value of my button as a variable

I thought this would be easy and I've googled it a bit but couldn't find how to do it.

I have:

<html>
<head>
    <script>

var string1 = "pigs"
document.write(string1)

</script>

</head>
<body>

<input type = "button" value="string1" id="button">
</body>
</html>

How do I get the value of the button to say 'pigs'? I tried:

value=string1

value = document.write(string1)

value = "document.write(string1)"

but no luck, thanks.

Upvotes: 0

Views: 65

Answers (2)

Nevin
Nevin

Reputation: 3298

Just use : document.getElementById

document.getElementById("button").value = string1;

What you have used is document.write:

The write() method writes HTML expressions or JavaScript code to a document.

Upvotes: 0

bobthedeveloper
bobthedeveloper

Reputation: 3783

You should get the button first before you can assign a value to it.

document.querySelector("#button").value = string1;

Upvotes: 1

Related Questions