Kaka
Kaka

Reputation: 395

Javascript will not execute

Why will this work on for example, http://codepen.io/ but not when I try it on my webserver? Using wamp. This is how it should be: http://codepen.io/anon/pen/Ctsvp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style type="text/css">
#text {
width: 540px;
height: 50px;
overflow: hidden;
}

#submit {
display: none;
}
</style>
<script>
var textInput = document.getElementById('text')
, submitButton = document.getElementById('submit');
function checkTextValue() {
if (textInput.value !== '') {
submitButton.style.display = 'block';
} else {
submitButton.style.display = 'none';
}
}
</script>
</head>
<body>

<form action="#" method="post">
<textarea onkeypress="checkTextValue()" onkeyup="checkTextValue()" onchange="checkTextValue()" id="text"></textarea>
<input id="submit" type="submit" value="Submit">
</form>

</body>
</html>

Upvotes: 0

Views: 58

Answers (1)

Mimo
Mimo

Reputation: 6075

You should wait for the DOM to be ready, so change your code to:

<script>
document.addEventListener('DOMContentLoaded', function() {
    var textInput = document.getElementById('text')
        , submitButton = document.getElementById('submit');
    function checkTextValue() {
        if (textInput.value !== '') {
            submitButton.style.display = 'block';
        } else {
            submitButton.style.display = 'none';
        }
    }
});
</script>

Upvotes: 4

Related Questions