简体   繁体   中英

Simple JavaScript Doesn't Work

I have written the below mentioned javascript and have called on the button click event but somehow it doesn't work, please someone help.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
</head>
<script type="text/javascript">
function f1()
{
    var x=document.getElementById("txt1").innerHTML
    if(x==1)
    {
        alert("hello");
    }
}
</script>
<body>
    <form id="form1">
        <input type="text" id="txt1"/><br/>
        <input type="button" id="btn1" value="submit" onclick="f1()"/>
    </form>
</body>
</html>

它不应是.innerHTML ,而应是.value

You're trying to grab innerHTML from an input field when you should be grabbing the value otherwise it'll always be undefined :

Change:

var x = document.getElementById("txt1").innerHTML;

to:

var x = document.getElementById("txt1").value;

JSFiddle Example

http://jsfiddle.net/moogs/dNWNP/1/

You should use value instead of innerHTML :

var x=document.getElementById("txt1").value;

See the jsfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM