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

Dual Camera Toggle Functionality with Three.js Orbit Controls

I am facing an issue with two cameras in one scene, one viewport, and one renderer. I switch between cameras using HTML buttons. ISSUES Issue 1 When using camera1, there is no response from moving the mouse. However, when I switch to camera2, the orbit ...

Integrate geographic data in GeoJSON format into a Leaflet map by using the Django template

In my Django view, I am fetching results of an SQL query and rendering it on the index.html page of my web map. The POST request successfully returns the acreage calculated from the SQL query to the page. I am also attempting to display the geojson data fr ...

Why is the Google Map missing from the Bootstrap modal dialog?

I have multiple links on my website, each describing a different location with unique map data. I would like to display a modal bootstrap dialog with an embedded Google map when a user clicks on any of the links - ensuring that the location shown correspon ...

Error: Unable to access properties of an undefined value (trying to read 'type') within Redux Toolkit

Looking for help with this error message. When trying to push the book object into the state array, I encounter an error. Folder structure https://i.stack.imgur.com/9RbEJ.png Snippet from BookSlice import { createSlice } from "@reduxjs/toolkit" const ...

Exploring the differences between jQuery's methods for retrieving text, HTML, JSON

I'm feeling a bit perplexed: When I use the following code: $.get('http://externhost/somefile.js', callback, 'text'); I receive the error message: XMLHttpRequest cannot load http://externhost/somefile.js. Origin http://www.myho ...

Comparing the Length of JavaScript Arrays

I have code that checks for similar values in two arrays, and if there are any, they are not displayed in the result. However, when I switch the lengths of the arrays so that Array2 is longer than Array1, I end up with an empty result array. How can I achi ...

Shadows for directional light in three.js

http://jsfiddle.net/wp6E3/3/ var camera, scene, renderer; var cubes = []; init(); animate(); function init() { scene = new THREE.Scene(); scene.add(new THREE.AmbientLight(0x212223)); for (var i = 0; i < 10; i++) { var cubeGeomet ...

Unable to retrieve the complete count of invitations made by a user

My goal is to retrieve the invites of the author of a specific command within one server. I have experimented with various solutions, but many appear outdated or incorrect. Here is my current approach: exports.run = async (client, message, args) => { ...

When working with Next.js, I encountered a scenario where the useEffect() function was being triggered twice. I attempted to solve this issue by providing an empty array as the second argument, but to no

When working with Next-JS, I encountered an issue where the useEffect() function was running twice. While I heard that using an empty array as the second argument can fix this in React, it did not work in my case within Next-JS (which is based on React). ...

Verify if the form has been successfully validated

Here is a simple form using Tag Helper: <form asp-area="Admin" asp-controller="Categories" asp-action="EditCategory" method="post" id="CategoryForm"> <div class="row"> ...

Hindering advancement: Bootstrap Form Wizard causing roadblocks

I am currently facing an issue with my form wizard setup. I want to prevent the user from advancing to the next step when the success key in my json is set to false. It seems like the project is utilizing the bootstrap wizard plugin. You can find more in ...

Steer clear of manually inputting URLs in your React components

As I embark on my journey with Gatsby, I am noticing a recurring pattern in my code. A prime example is when creating links, where I often find myself doing something like this: import {kebabCase} from "lodash"; // ... <Link to={`tags/${kebabCase( ...

Improving the efficiency of ajax/javascript is necessary as the delay in data retrieval is too significant. There must be a more effective approach to this

Utilizing ajax requests to populate modal popup windows with user-filled data has been my current method. These popup windows, designed as div layouts, are controlled by jquery for showing and hiding. However, there seems to be a noticeable delay in this p ...

How can I show a view page in a specific div element using CodeIgniter?

Here is how I'm implementing the dashboard view in my controller. My goal is to have a specific page, like the index page, displayed within a div element rather than opening in a new tab. public function index() { $this->load->view('in ...

Gulp: Adding to Dest without Overwriting

I have the following code snippet: gulp.task('concat-uglify-js', function() { return gulp.src(src + 'js/*.js') .pipe(concat('angular-filemanager.min.js')) .pipe(uglify()) .pipe(gulp.dest(dst)) }); gulp.task(&ap ...

What can be achieved through JSON deserialization and extracting data from fields?

Below is the data that I received from the REST service: { "category_id": 1314, "display_category_name": "", "english_category_name": "Sports", "url_category_name": "" }, { "category_id": 13, "display_category_name": "Art", "en ...

How can I implement the self-clearing feature of a timer using clearInterval in ReactJS?

I am a newcomer to the world of React and I am currently working on creating a React component with multiple features. Users can input a random number, which will then be displayed on the page. The component includes a button labeled 'start'. W ...

Display the keys of a nested array in Vue.js when the structure is unknown

Here is a representation of a dynamic array I have: nodes: [ { n1: "Foods", }, { n4: "Drinks", b7: [ { a2: "Beers", a4: [ ...

Tips for updating Angular HTML with data received from Socket.IO

I am currently working on a socket program that is listening and providing log data. The socket is sending the correct data as I can see it in the console. Below is a snippet of my code: export class RoboLogComponent implements OnInit { dataToShow:any @V ...

Error: Syntax mishap detected - Oh dear

Recently, I've been developing a small slideshow / public display for a client using the HTML5 Rock's Slideshow code. Everything was going smoothly until I encountered a DOM Exception 12 - an error related to CSS selectors. Strangely, I couldn&ap ...