Thursday, June 9, 2016

How to detect enter key pressed on HTML textbox

Question: How to detect enter key pressed on HTML textbox


Below is HTML syntax, now when user write on textbox we need to track enter key

<input type="text" placeholder="Search"  id="txtSearch" class="search-query form-control">
                    <span class="input-group-btn">
                        <button type="button" id="btnSearch" runat="server" class="btn btn-danger"><span class=" glyphicon glyphicon-search"></span></button>
                    </span>

Solution: you need to add onKeyPress event to the textbox and write javascript function as below

onKeyPress="fnSearchClick(event, this)"

<script type="text/javascript">
    function fnSearchClick(e, textarea) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //Enter keycode
            document.getElementById('btnSearch').click();
        }
    }
</script>

No comments:

Post a Comment