Home > Software design >  JavaScript function only fires when there are 2 input boxes
JavaScript function only fires when there are 2 input boxes

Time:09-30

I have an aspx page in Visual Studio. I have a function which fires on the onkeyup. When I have just the single control on the page, the JavaScript function is not called. When I add a second control, the JavaScript is called.

With this code, the JavaScript does not fire...

<form id="form1" runat="server">
    <div>
        <div class="form-group">
            <label for="barcode">Barcode</label>
            <input type="text" onkeyup="searchBarcode()" class="form-control" id="txtBarcode" name="barcode" />
        </div>
    </div>
</form>
<script>
    function searchBarcode() {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            alert('Hello');
        }
    }
</script>

With this code the JavaScript fires

 <form id="form1" runat="server">
        <div>
            <div class="form-group">
                <label for="registration">Registration</label>
                <input type="text" class="form-control" id="txtRegistration" name="registration" />
            </div>
            <div class="form-group">
                <label for="barcode">Barcode</label>
                <input type="text" onkeyup="searchBarcode()" class="form-control" id="txtBarcode" name="barcode" />
            </div>
        </div>
    </form>
    <script>
        function searchBarcode() {
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if (keycode == '13') {
                alert('Hello');
            }
        }
    </script>

CodePudding user response:

Try this

<script>
        window.onload = function () {
            document.getElementById('txtBarcode').addEventListener('keyup', keyEvent)
        }

        function keyEvent(e) {
            var keycode = (e.keyCode ? e.keyCode : e.which);
            if (keycode == '13') {
                alert('Hello');
            }
        }
    </script>

CodePudding user response:

You are missing passing event to the function

<form id="form1" runat="server">
    <div>
        <div class="form-group">
            <label for="barcode">Barcode</label>
            <input type="text" onkeyup="searchBarcode(e)" class="form-control" id="txtBarcode" name="barcode" />
        </div>
    </div>
</form>
<script>
    function searchBarcode(event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            alert('Hello');
        }
    }
</script>
  • Related