Reputation:
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
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