Using JavaScript to assign a value to ASP textboxes

While browsing through similar questions, I noticed that my query has a unique twist. I am working on a timesheet web app where employees submit their time in a table, which is then sent to H.R. in readonly mode. H.R. can approve or reject the timesheet based on specific criteria. To make it easier for H.R. Reps to identify incorrect entries, I came up with the idea of allowing them to click on cells and turn them red if needed. This way, when the timesheet is rejected and returned to the employee, they can easily see what needs correction.

I have written a small snippet in Javascript:

    var validTextArray = {};
    var backgroundColorArray = {};
    function clearTextBox(textBoxID) 
    {
        if (document.getElementById(textBoxID).value != "#ERROR")
        {
            backgroundColorArray[textBoxID] = document.getElementById(textBoxID).style.backgroundColor;
            validTextArray[textBoxID] = document.getElementById(textBoxID).value;
            document.getElementById(textBoxID).value = "#ERROR";
            document.getElementById(textBoxID).style.backgroundColor = "red";
        }
        else if (validTextArray[textBoxID] != null)
        {
            document.getElementById(textBoxID).value = validTextArray[textBoxID];
            document.getElementById(textBoxID).style.backgroundColor = backgroundColorArray[textBoxID];
        }
    }

To make sense of my c# script, here's a snippet:

            day1PH.Attributes["onclick"] = "clearTextBox(this.id)";
            day1PN.Attributes["onclick"] = "clearTextBox(this.id)";
            day1LV.Attributes["onclick"] = "clearTextBox(this.id)";
            day1TL.Attributes["onclick"] = "clearTextBox(this.id)";

            day2PH.Attributes["onclick"] = "clearTextBox(this.id)";
            day2PN.Attributes["onclick"] = "clearTextBox(this.id)";
            day2LV.Attributes["onclick"] = "clearTextBox(this.id)";
//etc...

The functionality works perfectly, but I am facing an issue capturing those errors. When H.R. rejects the timesheet, all data is rewritten to an SQL Database. However, as the text was set by Javascript using "#ERROR" values, they do not get transferred over.

How can I capture these values effectively?

Answer №1

If you are working with webforms, one way to handle errors is by using a hidden field to store the error message. You can set the value of this hidden field with the error message and then retrieve it on the server side when the form is submitted.

<input id="hdnErrors" type="hidden" name="error" value="xpto">

string error = Request.Form["error"] + ""; //error will be 'xpto'

If you have multiple errors, you can use a JavaScript dictionary to store them, serialize it into a JSON object, and then place it in the hidden field value. On the server side, you can deserialize the JSON object and process the errors accordingly.

Here's an example (not tested)

var arrayObject = [];
var error = {txtId = "txt1", description="HR error"};
arrayObject.push(error);

document.getElementById('hdnErrors').value = JSON.stringify(arrayObject);

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

Ways to automatically close browser tab upon successful submission of a form

I have an old file that has been updated. One of the requirements for this file/project modification is to have the current browser window close when the user clicks OK to submit the form. I am curious if this can be done using plain/vanilla JavaScript? ...

Creating a curved exponential data set with specific endpoints and a set number of data points

Struggling to create a function that involves math skills, I could really use some assistance. The task is to design a function that takes data points x and generates an array of size x with exponentially increasing values from 0 to 100. It would be ideal ...

Guide on sending SMS to mobile devices from a web application using ASP.NET and C#:

What is the process for sending an SMS message to a mobile phone from a web application using ASP.NET and C#? ...

Update the multidimensional array function to ES6 syntax

I'm in the process of developing a function for my app and I'm curious if there's a more elegant way to implement it using ES6, without relying on two for loops. The goal is to create a multi-dimensional array that keeps track of x and y co ...

adding a JavaScript module to a handlebars template

I have a few different files that I'm working with: In the server.js file, I have the following code: app.get('/main/:id', function(req, res) { res.render('main', { products: products }); }) Within the main.hbs file, I have ...

Swiper.IO pagination indicators not displaying

Why is the pagination not showing up on the image carousel I created with Swiper? Despite being in the DOM, it has a height of 0 and manual changes have no effect. Any suggestions? import Swiper from '../../vendor/swiper.min.js'; export default ...

Fill a Vuetify select component with options from a JSON array

Having just started with VUEJS, I am facing a challenge in populating a vuetify select element with the names of countries from a local JSON file that contains an array of JSON objects. Instead of displaying the options correctly, it is creating individual ...

Customize the size of data points on your Angular 2 chart with variable

In my Angular 2 application, I am utilizing ng2-charts to create a line chart. The chart functions properly, showing a change in color when hovering over a point with the mouse. However, I want to replicate this behavior manually through code. Upon clicki ...

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

The issue of req.file being undefined when using Multer in Node.js with Express Router

I have been working on incorporating File Upload capability utilizing multer and Express Router. I set up an endpoint /batch_upload using router.use in the following manner: api.js router.use( "/batch_upload", upload.single("emp_csv_data"), userCo ...

Leveraging JavaScript to identify web browsers

I am looking to implement a feature on my website where if the visitor is using Internet Explorer 8.0 or an earlier version, they will receive an alert prompting them to upgrade their browser before proceeding. For users with other browsers, the page will ...

LINQ may return null even when the condition is satisfied

Uncertain about the reason for this occurrence, I noticed it while in debugging mode and confirmed that the condition inside the LINQ statement was satisfied if (chkSometing.Checked) { var _results = from itemlist in dtResult.AsEnumerable() ...

What is the proper way to implement SSE/EventSource in your project?

After watching tutorials online, it seems common practice for authors to use SSE/EventSource in setting up a connection where the server-side PHP script echoes data and then uses ob_flush() and flush() to send the information back to the client's brow ...

Modifying the URL of an AJAX call prior to sending

I am looking to dynamically insert the data entered in a text box labeled 'postcode' into the URL parameters 'VALUE1' and 'VALUE2'. Unfortunately, I lack examples to provide as I am unsure of where to begin. <input type="t ...

Embracing PWAs with subdomains – seamless installation

One of my Progressive Web Applications (PWA) called app A contains a link to another app, app B. Initially, I hosted both apps on the same subdomain (for example: ) and everything worked perfectly - installing app A also installed app B. However, when I a ...

Pattern matching for traversing object properties

Is there a dependable method to match property-syntax using a Javascript regex? My goal is to identify whether a string contains a path structure, without the need to extract the specific members. For instance, if I have a string such as: someobject.somek ...

What is the best way to execute a loop while asynchronously calling a service in .NET Core 6 and ensuring that it waits for the result at the end

Seeking ways to enhance performance and minimize data display delay for users. The job involves retrieving data from multiple sources, processing it sequentially which is time-consuming. Looking for suggestions on boosting performance by making asynchrono ...

Dealing with asynchronous requests in Axios: A guide to solving the challenge

I'm working on a page named _id.vue in my Nuxt.js project: <template> <div class="wrapper"> <HeaderApp> <DivHeaderMenu> </DivHeaderMenu> </HeaderApp> <CenterContentDinamicFirmeni ...

How can I manually include a triangle in BufferGeometry using Three.js?

Recently, I've been exploring the quickest method to change a mesh's vertices using three.js. Through my experimentation, I discovered that modifying parts of mesh.geometry.attributes.position.array and then setting mesh.geometry.attributes.posit ...

Updated the object in an array retrieved from an API by adding a new key-value pair. Attempted to toggle the key value afterwards, only to find that

Essentially, I am retrieving products from an API and including a new key value isAdded in the object within the products array. I utilized a foreach loop to add that key and it was successfully added. Now, when I click the Add to cart button, the product ...