Guide on removing a textbox value in ASP.NET through scripting

I am facing an issue with a textbox in my asp.net application that accepts various values. I have written a script to clear the values from the textboxes every time I press the F5 button. However, when I run the code and hit F5, the values in the textboxes still exist. How can I resolve this?

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="wellDesigned0428._default" %>

<!DOCTYPE html>
<script runat="server"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="~/StyleSheet1.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
    <form id="form1" runat="server">
        <div class="body">
            <div class="content ">
          <asp:TextBox ID="txtCodePers" runat="server" CssClass="textbox" AutoPostBack="True" OnTextChanged="txtCodePers_TextChanged" MaxLength="4" ></asp:TextBox> 
           <asp:TextBox ID="txtName" runat="server" CssClass="textbox"></asp:TextBox>   
        </div>
    </form>
        <script type="text/javascript">
            document.onkeydown = checkKey;
            document.onkeyup = checkKey;
            document.onkeypress = checkKey;
            function checkKey(e) {
                if (e.keyCode == 116) {
                    alert("F5 key pressed");
                    document.getElementById("txtCodePers").value = "";
                    document.getElementById("txtName").value = "";
                }
            }
        </script>
</body>
</html>

Answer №1

It seems like the problem lies with the identifier you are using, txtCodePers, as it is a server-side id. It would be better to either set the clientid or inspect the source code to find out the correct id for txtCodePers.

In addition, I advise against overriding the default functionality of the F5 key, which is used for refreshing. Consider what might happen if the user uses the mouse or browser button to refresh instead.

Answer №2

If the ClientID of your TextBox does not match the one in the ID property, your JavaScript will not be able to locate the elements.

To resolve this issue, you can either utilize the ClientID in your script or simply add the ClientIDMode property to your textboxes:

ClientIDMode="Static"

This will ensure that the ClientID matches the ID, eliminating the need to modify your JavaScript code.

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

The issue with adding rows to a dynamic HTML Table in Angular is that it is causing the previous rows to disappear

I have created a neat HTML table with three columns: <table > <thead> <tr> <td class="tdBorderEmail"><label>Action</label></td> <td class="tdBorderEmai ...

Inner output not displaying on the screen

Based on the outcome of the graphql query, certain items are generated within the function contact export const Whitelist: React.FunctionComponent = (props) => { const [userData, setUserData] = useState<UsersQueryHookResult>(''); c ...

The JavaScript function on the specified /url page is not functioning properly following the execution of history.push(/url) on click

I have a JavaScript function that toggles the display of login password. However, when I redirect to the login page from another page using history.push(/login), the function does not work. It does work when I use (/login) in the href tag. How can I resolv ...

Guide to inserting an HTML file into an article's content

After downloading an extension from freefrontedit and uploading it to my server in the directory /accordeon, I successfully accessed it by pointing my browser to . However, I am now faced with the challenge of loading the index.html into my Joomla article ...

How can I update the image src in JavaScript and make sure the image refreshes properly?

I managed to update the image source in JavaScript code, changing it from: http://loclhost:8080/mvc/resources/pics/625bd317-b71c-4d74-aff2-248b86ff900b.jpg to http://loclhost:8080/mvc/resources/pics/4c1541ab-204c-4eff-b641-8527294e02cd.jpg Here is the ...

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

Tips for incorporating a seamless and interactive parallax effect into your React application

My task involves creating a unique landing page for a website using React. One of the key features I want to include is a parallax effect. The initial layout will have a transparent navbar at the top, along with a header, subtitle, and background image tha ...

Not able to increase value using 'wheel' event listener

I'm experimenting with incrementing a variable based on whether someone scrolls down or up the page. The event triggers each time you scroll in either direction, but the value only increases by one. Can anyone suggest a reason for this behavior? win ...

I am experiencing difficulties with a basic Angular JS application as it is not functioning as expected and

My Angular JS application seems to be having some issues. I have the following code structure with Index.js as the main file and controller.js as a script file. However, when I try to run the app, no errors are displayed in the browser: var app = angul ...

How to clear an HTML text input using JQuery

Can someone help me with adjusting the default value of an HTML text input using JQuery event handlers? I want to set it to empty. Here is the input: <button id="setColor">Set Color</button> <input type="text" id="colorText"> This is t ...

Sending data to callback functions

In the process of developing a jQuery plugin designed to be applicable to a selector, I encountered a challenge related to maintaining the current context item within the each loop of the selector. The plugin involves making multiple calls to webservices w ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

Ways to separate two pieces of information within a single element of an array

I am working with an array and trying to split two sets of data that are contained within one element of the array. Take a look at the code below : const array = ["1 Boston 4 11", "2 Florida 6 14\n3 Texas 5 12", "4 California 7 13"]; array.map(x ...

What is the best way to retrieve $scope in AngularJS using JavaScript?

Check out this demo on JSFiddle: http://jsfiddle.net/altermind/yak10smq/1/ In the controller 'EntrynewCtrl', I am trying to declare a variable called 'appetite' and pass it to a JavaScript function like this: <script> var ...

The TryUpdateModel function is not functioning correctly

Currently, I am working through the examples provided in Professional ASP.Net MVC 2. However, I have encountered an issue with one of the examples as it is not functioning correctly for me. [HttpPost] public ActionResult Edit(int id, FormCollection collec ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

Guide to customizing the default scrollbar colors in Nextjs

When browsing websites like tailwindcss.com or https://developer.mozilla.org/ in Chrome and Firefox, you may have noticed that they utilize the default scrollbar style but allow users to change its colors through a dark/light mode button. The appearance of ...

Unable to retrieve variable declared externally from Switch Statement

Having an issue with assigning a value to the variable contactNumber inside a switch statement. Upon reaching the assignment line, an error SyntaxError: Unexpected identifier is triggered within the switch statement context. function contactMessageForCo ...

Calculate the total rows within a specified date range

Within my database, there is a column named IsStaff, which returns a value as a bit. This signifies whether a staff member in a company has an illness (1) or not (0). How can I construct an SQL query to count the occurrences of both 1's and 0's w ...

Issues with React components failing to render due to dependencies

Currently, I am immersed in the React tutorial and endeavoring to construct a React/Express application using the repository located on GitHub. In the instructional material, all React dependencies are outlined within the index.html file: <!DOCTYPE ...