我的JavaScript代码有什么问题?

时间:2010-12-30 10:08:51

标签: javascript checkbox

现场代码:http://jsfiddle.net/nnMYN/

如果用户选中“与上面相同”复选框,我必须“自动将邮政地址复制到家庭住址字段。”除此之外,我们将在选中复选框后禁用家庭住址字段。 (from here)我做错了什么?

<html>
    <head>
    </head>
    <body>
        <form>
            <fieldset>

                <legend>Billing Information</legend>

                <p>
                    <label>
                        Postal Address:<br>
                        <textarea name="postaladdress" id="postaladdress"></textarea>
                    </label>
                </p>

                <p>
                    Home Address:<br>
                    <label>
                        <input type="checkbox" name="homepostalcheck" id="homepostalcheck">
                        Same as above
                    </label>
                    <br>
                    <textarea name="homeaddress" id="homeaddress"></textarea>
                </p>

            </fieldset>
        </form>
        <script type="text/javascript">
            var loc = document.getElementById('homepostalcheck');
            var home = document.getElementById('homeaddress');
            loc.onclick = !loc.checked ? function() {home.disabled = true; home.value = post.value; alert(post.value);} : function() {home.disabled = false; home.select();};
        </script>
    </body>
</html>

2 个答案:

答案 0 :(得分:2)

添加

var post = document.getElementById('postaladdress');

您一直尝试访问value对象的参数post,但没有这样的post对象,因为您尚未定义它。如果在定义home后添加上面的行,则应该设置!当我在jsFiddle上编辑它时它起作用了。

答案 1 :(得分:0)

尝试将javascript放在function(){

<script type="text/javascript">
    (function() {
        var loc = document.getElementById('homepostalcheck');
        var home = document.getElementById('homeaddress');
        loc.onclick = !loc.checked ? function() {home.disabled = true; home.value = post.value; alert(post.value);} : function() {home.disabled = false; home.select();};
    });
</script>