Javascript无法获取文本输入的值

时间:2015-04-25 14:40:02

标签: javascript html

如果我手动设置command的值,下面的代码可以正常工作,但如果我尝试动态获取值,则代码将完全停止工作。我隔离了似乎是问题的代码行(在它说错误之后的注释)。

如果我对该行alert(document.getElementById("cdmTxt").value);发表评论,则按预期工作。

<?php
session_start();
?>
<!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>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script type='text/javascript'>

function exec(){
    alert("hi");
    alert(document.getElementById("cdmTxt").value); //does not seem to execute???
    var command = "word";
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var txtToUpdate = document.getElementById("txtHint");
            txtToUpdate.innerHTML = txtToUpdate.innerHTML + xmlhttp.responseText + "<br/><br/>";
        }
    }
    xmlhttp.open("GET", "HAS-sync.php?exec=" + command, true);
    xmlhttp.send();
}
</script>
<style type="text/css">
.auto-style1 {
    margin-top: 0px;
}
</style>
</head>

<body>

<table style="width: 100%">
    <tr>
        <td style="width: 141px; height: 390px">Managers<br /> DHTs</td>
        <td name="targetThing" style="height: 390px">
            <form onsubmit="exec();return false">
                <input id="cmdTxt" class="auto-style1" name="Text1" type="text">
                <input type="submit">
            </form>
            <br />
            <div id="txtHint" style="overflow: scroll; border:1px solid black;width:80%;height:80%"></div>
        </td>
    </tr>
</table>

</body>

</html>

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

你有一个错字:

getElementById("cdmTxt") // It should be "cmdTxt"