Javascript How do i compare two values and then change background color?

Why doesn't this code work? I want it to change the color of the input background whether the value is correct (green) or not (red).

<html>
<head>
<script type="text/javascript">
function funct1 () {
var username = "63XZ4";
if(username == document.getElementById('keygen').value ) {

document.getElementById('keygen').style.backgroundColor = '#5bc556';
}

else {
colorchange.style.backgroundColor = 'red';
}
}
return 0;
</script>
</head>
<body>
<input type="text" id="keygen">
<button onclick="funct1"></button>
</body>
</html>

<html>
<head>
<script type="text/javascript">
function funct1 () {
    var username = "63XZ4";
    var keygen = document.getElementById('keygen');
    if(username == keygen.value) {
        keygen.style.backgroundColor = '#5bc556';
    } else {
        keygen.style.backgroundColor = 'red';
    }
}
</script>
</head>
<body>
<input type="text" id="keygen" />
<button onclick="funct1()">Button Title</button>
</body>
</html>

The above should help. Also, you may want to look into this:

  • Give more descriptive names to functions you declare.
  • Save time by eliminating calls to "getElementById" by storing DOM elements in variables.
  • 链接地址: http://www.djcxy.com/p/70508.html

    上一篇: 基于条件语句更改文本背景的颜色

    下一篇: Javascript如何比较两个值然后更改背景颜色?