Tuesday, February 7, 2012

[JS] 用JavaScript抓取Enter事件並按下按鈕

有個需求是要在條碼機讀到資料時,就查詢該筆資料....

條碼機送出的資料是一串文字加一個 enter ,原本網頁要做到 enter submit form 是很簡單的,沒記錯 action 設一下就好,但是有的時候不能改 form action,只好用 js 去克服了,原本寫在 .net 上的版本我是在 textbox 上加 onkeypress 去觸發事件,但是拿到blog上我就改用jQuery以方便展示了。



上面是demo,下面是語法。

HTML部分
<input id="tbSearch" type="text" name="tbSearch"> 
<input id="btnSearch" type="button" value="按我" onclick="showtxt()"> 
<div id='showhere'></div>

JavsScript部分
$('.tbSearch').keypress(function(e) {
        var key = window.event ? e.keyCode : e.which;
        if (key == 13)
            $('btnSearch').click();
    });

    $(document).ready(function () {
        $('#tbSearch').focus();
    });

    $('#tbSearch').keypress(function(e) {
        if(e.which == 13) {
            $('#btnSearch').focus().click();
        }
    });

    function showtxt() {
        $('#showhere').text($('#tbSearch').val());
    }


記得要引用jQuery,不然不會動。

1 comment:

  1. Cartier watches boast a large variety replica watches of design and functionality, replica calibre de cartier watches yet maintain replica cartier tank mc watches the utmost quality and sophistication in every series. Crafted from the finest steel, rose gold, yellow gold, and white gold, and utlizing the highest grade of diamonds worthy of the Cartier name, Cartier has dominated the industry of elegant watches. Mens and ladies watches alike are assured attention to detail internally and externally, and the namesake itself is a milestone in the world for which the standard of reputation alone is reminiscent of the product.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...