user3638277
user3638277

Reputation:

Learning Javascript, why doesn't this work?

I'm trying to learn some javascript but it is driving me nuts already...
Why won't this work? i can get data to show without a button, but with the button it just does not work for some reason and i dont understand why

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jstest</title>
</head>

<body>
<button type="button" 
onclick = "document.getElementById('cars').innerHTML = cars[0]">
<p>asdf</p>
</button>

<script>
var cars = ["Saab", "Volvo", "BMW"];
</script>

<p id="showdata"></p>

</body>
</html>

Upvotes: 1

Views: 61

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You need an element with an id with 'cars' for

document.getElementById('cars').innerHTML = ...
//                      ^^^^^^

var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("showdata").innerHTML = cars[0];
<button type="button" 
onclick = "document.getElementById('cars').innerHTML = cars[0]">
<p>asdf</p>
</button>
<p id="showdata"></p>
<p id="cars"></p>

Upvotes: 1

Related Questions