document.getElementById(' TextBox1')。value无效

时间:2016-03-04 17:25:33

标签: javascript c# asp.net

我想在javascript中获取文本框的值。这是我的javascript -

<script type="text/javascript">
    var submitted = false;  var type;
    window.onbeforeunload = function () { 
        if (!submitted) { 
            return "Are you sure you want to leave this page, your test will not be saved?"+type; 
        }
    }; 

    document.getElementById('form1').onsubmit = function () { 
        type=document.getElementById('TextBox1').value; 
        submitted = true;
    }; 
</script>

无论我输入什么,它都不会给我textbox1的价值

2 个答案:

答案 0 :(得分:0)

 <script type="text/javascript">
        var submitted = false; var type;
        $(document).ready(function ()
        {
            $('#form1').submit(function ()
            {
                type = document.getElementById('TextBox1').value;
                submitted = true;
            });
            window.onbeforeunload = function ()
            {
                if (!submitted)
                {
                    return "Are you sure you want to leave this page, your test will not be saved?" + type;
                }
            };
        });



    </script>

if you want to display type's value in alert box then,change if(!submitted') to if(submitted) and you will receive an alert with type value.hope this will do.

答案 1 :(得分:0)

这看起来只是一个逻辑问题:

当您运行onsubmit时,它会将submitted设置为true,然后运行onbeforeunload。现在它基本上只返回输入值,如果你没有运行onsubmit。如果您从!中取出(!submitted),它会向您发送包含输入值的提醒。