Display information using an ASP.Net barcode scanner

Currently, I am developing a WCF service application that involves receiving characters from a barcode reader and displaying the data on the UI for the user. My issue arises when inputting data using the keyboard into a textbox; everything functions correctly. However, reading data from the barcode reader causes the information to overwrite existing content in the UI multiple times.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Service and Barcode Reader</title>


    <script src="Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function setFocusToTextBox() {
            $(document).ready(function () {
                document.getElementById('txtFirst').focus();

            });
           }
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#txtFirst").keydown(function (e) {
            if (e.which == 17 || e.which == 74) {
                e.preventDefault();
            } else {
                console.log(e.which);
            }
        })
    });
</script>
    <script type="text/javascript" language="javascript">
        function JqueryAjaxCall(val) {
            $("#contentHolder").empty();
            $(".form-errors").empty();
              if (val != null && val.length === 20) {
                  document.getElementById("txtFirst").select();
                var pageUrl = '<%= ResolveUrl("~/Default.aspx/jqueryAjaxCall") %>';
                var parameter = { "myVal": val}

                $.ajax({
                    type: 'POST',
                    url: pageUrl,
                    data: JSON.stringify(parameter),
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    dateFormat: 'dd/mm/yy',
                    success: function (data) {
                        onSuccess(data);
                    },
                    error: function (data, success, error) {
                        var myitems = jQuery.parseJSON(data.responseText);
                        $(".form-errors").text(myitems.Message).show();
                    }
                });

       return false;
        }

   function onSuccess(data) {

            var items = data.d;
            var fragment = "<ul>"
            var BLNumber = items.BLNumber;
            var ContainerNumber = items.ContainerNumber;
            var Destination = items.Destination;
            var SerialNumberVerification = items.SerialNumberVerification;
            var TempPermission = items.TempPermission;
            var VehicleNumber = items.VehicleNumber;
            var VehicleType = items.VehicleType;
            var VoyageID = items.VoyageID;
            var value = new Date(parseInt(items.ExitDate.substr(6)));
            var ExitDate = value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
            var ExitPermissionNumber = items.ExitPermissionNumber;
            var myvalue = new Date(parseInt(items.SpecialZoneOrCustomPermissionDate.substr(6)));
            var SpecialZoneOrCustomPermissionDate = myvalue.getMonth() + 1 + "/" + myvalue.getDate() + "/" + myvalue.getFullYear();
            var SpecialZoneOrCustomPermissionNumber = items.SpecialZoneOrCustomPermissionNumber;

                fragment += "<li> " + " Shipping Number : " + BLNumber + " <br> "
                                    + " Container Number : " + ContainerNumber + " <br> "
                                    + " Destination : " + Destination + " <br/> "
                                    + " Verification Number : " + SerialNumberVerification + " <br/> "
                                    + " Temporary Permission Number : " + TempPermission + " <br/> "
                                    + " Vehicle Number : " + VehicleNumber + " <br/> "
                                    + " Vehicle Type : " + VehicleType + " <br/> "
                                    + " Voyage ID : " + VoyageID + " <br/> "
                                    + " Exit Date : " + ExitDate + " <br/> "
                                    + " Exit Number : " + ExitPermissionNumber + " <br/> "
                                    + " Permission Date : " + SpecialZoneOrCustomPermissionDate + " <br/> "
                                    + " Permission Number : " + SpecialZoneOrCustomPermissionNumber + " <br/> "
                                    + "</li>";

                $("#contentHolder").append(fragment);
            }  
        }


    </script>

</head>
<body onload="setFocusToTextBox();" bgcolor="#E6E6FA">
    <form id="myForm" runat="server" dir="rtl" >
    <br /> 
    <br /> 
    <br /> 
    <br /> 
    <br /> 
    <br />
    <br />
    <hr />
    <div>
       <table cellpadding="1" cellspacing="0" style="width: 80%;">
            <tr>
                <td>
                </td>
                <td>
                    <asp:Label ID="lblFirst" runat="server" Text="Please enter the document number: " Font-Bold="True"></asp:Label>
                  <input type="text" id="txtFirst" onfocus="setFocusToTextBox"  onkeyup="return JqueryAjaxCall(this.value);" class="col-xs-4" style="background-color:#ede0dd"/>
                </td>

            </tr>
            <tr>
                <td>
                </td>
                <td>
                 <div id="contentHolder" >
                    <asp:Label ID="lblError" runat="server" Text=""></asp:Label>
                    </div>
                </td>
                 <td>
                    <div class="form-errors" style="margin-right:-175%;font-style:oblique" dir="rtl" align="right"></div>
                </td>
            </tr>
        </table>
    </div>
    </form>
     <br /> 
    <br /> 
    <br /> 
    <br /> 
    <br />
     <hr />
</body>
</html>

Answer №1

Within this code snippet, an AJAX call is triggered every time a key is pressed.

 onkeyup="return JqueryAjaxCall(this.value);"

This results in data being output each time a key is pressed, potentially multiple times. To improve efficiency, consider restructuring the code so that the rendering only occurs after typing is complete.

Answer №2

After some careful consideration, I finally figured out the issue with this line of code.

Instead of just using $("#contentHolder").append(fragment); like before,

I made a small adjustment by adding .empty() to it.

So now it looks like this: $("#contentHolder").empty().append(fragment);

The solution came to me after reading through this helpful link:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method available to minimize the size of a local storage list containing strings?

Hey there, I am trying to load a large 2.5MB json file in my browser so that I can use it for some typeAhead functions. Unfortunately, I'm facing an issue with my local storage being constantly full. When using Firefox, I receive the following error ...

What is the best way to maintain the position of components (such as a Card component) when one is expanded in a Material-UI and ReactJS project

Currently, I am working with an expandable Card component from Material-UI and using flex for aligning the components. However, when one card expands, it affects the positioning of the other components in the row: https://i.stack.imgur.com/vGxBU.png What ...

Is there a way to set an image as the background of my HTML screen?

{% extends "layout.html" %} {% block app_content %} <div> {% from "_formhelpers.html" import render_field %} <form method="post" enctype="multipart/form-data"> <div class = "container"> < ...

The ajax keypress event is malfunctioning and the ActionResult parameter is failing to capture any data

I am facing an issue where I want to update the value of a textbox using AJAX on keypress event, but the controller is not receiving any value to perform the calculation (it's receiving null). <script> $('#TotDiscnt').keypress(fu ...

Ensure that all content in the table rows remains visible, even in a table with unusually lengthy cells

My HTML table is structured like this: +-------------+-------------+----------+ | Single line | Single line | Very, | | | | very | | | | long | | | | text, | | ...

Issue encountered while attempting to log out a user using Keycloak in a React JS application

I'm currently working on implementing authentication for a React JS app using Keycloak. To manage the global states, specifically keycloackValue and authenticated in KeycloackContext, I have opted to use React Context. Specific Cases: Upon initial r ...

Arranging array elements by both date and alphabetical order using Javascript

Is there a way to sort the data by both date and alphabet at the same time? Alphabetical order seems fine, but the date sorting isn't working correctly. Thank you for any solutions. Data structure : [{ productId: 21, title: "Huawei P40 L ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

I am experiencing difficulties with displaying my array of JSX elements in the render function of my ReactJS application. What could be

I am currently working on a trivia application and encountering an issue with inserting an updated array of "Choice" elements for each question. Despite my efforts, whenever I attempt to insert an array of JSX elements, the array appears blank. This is qui ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

Having trouble exporting a variable from one Node.js file to another and finding that the value remains unchanged?

Hey there, I've been working on exporting a variable to another file within my nodejs application. I have successfully exported the variable, however, I need it to update whenever a user logs in. Will the export automatically pick up on this change an ...

How can I use JQuery to enable or disable checkboxes upon loading?

I am looking to implement a feature where the checkboxes are enabled when the .group is checked and disabled when it is unchecked. Although I can toggle between them, I'm facing difficulty in disabling the unchecked checkbox using the .group. Upon lo ...

Exploring the process of cycling through "Fetch" JSON data in React.js for a dynamic slider component after setting it to state

Still getting the hang of React, so please go easy on me! My main objective is to retrieve data from my personal JSON server and display it on a custom "Slider" component that I'm working on. Following a tutorial, I wanted to challenge myself by usi ...

Modifying the URL path while navigating through pages with ajax and jQuery

I have implemented ajax post requests to enable paging on a feed within my website. Upon receiving the post request data, I refresh the page by clearing out previous content and displaying the new data retrieved from the request. In addition to this, I wan ...

Customize the website's CSS for optimal viewing on an iPad

I have a website with two CSS files: one for viewing the site on a desktop screen and the other for viewing it on an iPad screen. Despite having the same HTML code, is there a way to detect the iPad device and force it to use the appropriate CSS file? Tha ...

Capturing jQuery ajax requests in Angular

Within my Angular application, I am utilizing the integrated $.couch API from CouchDB. My goal is to intercept every ajax request, regardless of whether it originates from Angular's $http service or jQuery's $.ajax (which is utilized by $.couch). ...

Displaying the Yii form directly on the page upon loading, rather than enclosed within a jQuery dialog box

After studying this yii wiki page, I encountered an issue where the form is supposed to appear within a jQuery dialog box, but it opens immediately when the page loads instead. Upon further investigation, I discovered that removing the success callback fr ...

Issue with returning value from promise object in Next.js

Hello! I am fairly new to JS and React, so I would appreciate your patience as I try to navigate through this. It has been quite a journey so far. In my component, I am fetching JSON data from a URL and attempting to extract a specific value from it to d ...

Stable and persistent popup window that remains at the forefront in a Chrome extension

Currently developing a Google Chrome extension and seeking assistance in creating a popup window that remains fixed in one corner while staying on top of all other windows. Here is a reference image for clarification: https://i.stack.imgur.com/IPw7N.jpg ...

Tips for modifying string in key-value pairs on the client side (example using Paypal checkout demo)

Looking to integrate an online payment system into my small online business, I have decided on using PayPal. Their solution is user-friendly and can be found here: https://developer.paypal.com/demo/checkout/#/pattern/client However, I am facing an issue w ...