更改焦点后取消onkeypress事件

时间:2011-09-24 18:43:55

标签: javascript javascript-events onkeypress

当输入是按下而不是提交表单时,我的用户希望此表单将焦点提前到下一个字段。我在测试输入中添加了一个onkeypress处理程序,以便在按下输入时更改焦点。

在下面的代码中,当keydown函数改变焦点时,我看到光标跳转到新文本框,但随后表单被提交,就像我再次按下回车键一样。我认为通过在我的事件处理程序中返回false,事件不会被传递,但似乎并非如此。我在Chrome和Firefox中都看到了这种行为。

有人能告诉我我错过了什么吗?

<form action="" name="confirmation" method="post">
    <fieldset>
        <div class="clearfix">
            <label for="id_event_fuel_amount">Quantity:</label>

            <div class="input">
                <input type="text" id="event_fuel_amount_id" name="event_fuel_amount" onkeypress="keydown(event, &#39;event_purchase_amount_id&#39;)" />

            </div>
        </div>
        <div class="clearfix">
            <label for="id_event_purchase_amount">Sale:</label>

            <div class="input">
                <input type="text" id="event_purchase_amount_id" name="event_purchase_amount" />

            </div>
        </div>


        <input type="hidden" name="state" value="3" id="id_state" />

        <input type="hidden" name="time_stamp" value="2011-09-24 14:34:06" id="id_time_stamp" />

        <input type="hidden" name="purchase" value="66" id="id_purchase" />


        <input type="submit" value="Save"/>
    </fieldset>
</form>

<script>
    function keydown(e,s){
        if (!e) var e = window.event;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        if (code==13){
            document.getElementById(s).focus();
            return false;
        }
    }
</script>

2 个答案:

答案 0 :(得分:0)

尝试

e.preventDefault();

这应该可以防止事件触发表单提交。

答案 1 :(得分:0)

我认为这可能会有所帮助:

<script type="text/javascript">
document.getElementById('hello').onkeydown=function(e){
    var e=window.event || e;
    if (e.keyCode == 13) return false;
}
</script>
<input type="text" id="hello" />

以下是演示:jsFiddle demo

相关问题