Styling a textbox within a gridview using JavaScript

Looking for a way to format a textbox within a gridview using JavaScript? Take a look at how the gridview columns are set up:

<Columns>
    <asp:TemplateField>
        <ItemTemplate><asp:ImageButton runat="server" id="imgbtnEnterAmt" ImageUrl="~/Images/bullet_list.png" Width="12px" Height="12px" OnClick="imgbtnEnterAmt_Click" /> </ItemTemplate> 
    </asp:TemplateField>

    <asp:BoundField DataField="particulars" HeaderText="HOSPITAL CHARGES/ PARTICULARS" />

    <asp:TemplateField HeaderText="ACTUAL">
        <%--<ItemTemplate><asp:TextBox runat="server" ID="txt_ipamt" OnTextChanged="txt_ipamt_TextChanged" AutoPostBack="true"></asp:TextBox> </ItemTemplate> --%>
        <ItemTemplate><input type="text" id="txth_ipamt" onblur="format_amt()" /> </ItemTemplate>
    </asp:TemplateField>

    <asp:BoundField DataField="deductions" HeaderText="DEDUCTION/ PHILHEALTH" />
</Columns>

In order to execute proper formatting of the textbox, here is the associated JavaScript function:

function format_amt()
        {
            var str_amt = document.getElementById('txth_ipamt').value;
            var n = parseFloat(str_amt).toFixed(2);
            document.getElementById('txth_ipamt').value = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }

An issue arises when adding more rows as only the first textbox gets formatted upon blur. Additionally, triggering the blur event again results in double formatting and incorrect output.

Answer №1

To modify the call to your JavaScript function and include the textbox as a parameter, utilize the this keyword.

<input type="text" id="txth_ipamt" onblur="format_amt(this)" />

Subsequently, within your function, make use of the passed parameter.

function format_amt(textbox)
{
    var str_amt = textbox.value;
    var n = parseFloat(str_amt).toFixed(2);
    textbox.value = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

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

What is the reason why a Reactive object in reactiveUI is unable to be serialized using Newtonsoft.Json?

While attempting to serialize a ReactiveObject from ReactiveUI, I discovered that it was being serialized to null data within the JSON text. public string Get() { return JsonConvert.SerializeObject(Value, Formatting.Indented); } T ...

Getting the specific information you need from a JSON object in Angular 2

Struggling to extract specific data from a JSON file with nested objects like this: { "results" : [ { "address_components" : [ { "long_name" : "277", "short_name" : "277", "types" : [ "street_number" ] ...

What is the method of including a null option in a dropdown menu?

I have a basic dropdown menu with the placeholder text "none." I want users to be able to clear their selection without adding another option to the dropdown. Can anyone help me achieve this? Thank you! Below is my code snippet: Check out the live demo h ...

Achieving a seamless global database connection throughout an application in .NET Core using MongoDB

Being new to using .net core, I am embarking on creating rest apis with MongoDB. My primary concern lies in establishing a universal database connection and global configuration for accessing any collection within the database. Researching online, I discov ...

Empower the user with the ability to interact through touch on dynamically

I am trying to make a div touchable and draggable. I have dynamically created 1 to 10 divs within another div. Currently, these divs can only be dragged using the mouse or cursor. However, I want to enable dragging through touch as well. Can anyone provi ...

NextJS allows for custom styling of Tiktok embeds to create a unique and

Currently, I am in the process of constructing a website that integrates Tiktok oEmbed functionality. Thus far, everything is running smoothly, but I have encountered an issue - how can I customize the styling to make the body background transparent? I ha ...

Can a function be passed to the URL field in an AJAX request?

Can a function be passed to the url field in an ajax call? I am looking to dynamically change the url being used in the ajax call. function generateURL(){} $.ajax({ url: generateURL, context: document.body, success: function(){ $(this).addCla ...

The bot believes it's jamming out to some tunes, but there's nothing but silence in the realm

Essentially, a slash command is utilized to initiate playing a music video in Distube. It plays for approximately 30 seconds and then abruptly stops, even though the queue indicates that the music is still playing. There are no errors appearing in my termi ...

Directive in AngularJS fails to trigger upon form reset

I encountered an issue with a directive used within a form, specifically when clicking on a button with the type reset. The problem can be replicated on this stackblitz link. The directive I'm using is quite simple - it sets the input in an error stat ...

Imagine a scenario where clicking on an image causes it to be rotated or

Could use some assistance figuring out what's missing here. I've added a random photo from Wiki, similar in size to the images I'll be working with. The images will vary in size, but I want them to always remain visible within the browser w ...

Is there a way for me to adjust my for loop so that it showcases my dynamic divs in a bootstrap col-md-6 grid layout?

Currently, the JSON data is appended to a wrapper, but the output shows 10 sections with 10 rows instead of having all divs nested inside one section tag and separated into 5 rows. I can see the dynamically created elements when inspecting the page, but th ...

"Unleashing the Power of Effortless Object Unwr

Looking for a better way to convert a raw json snapshot from Firebase into a JS class. My current method is lengthy and inefficient. Does anyone have a more optimal solution? Class: class SuggestedLocation { country_slug region_slug slug marker_ty ...

Vue.JS is throwing a TypeError: Unable to employ the 'in' operator to look for 'undefined' within the Laravel Object

How can I successfully pass an object from Laravel to Vue.js and utilize it in a v-for="option in this.options"? Although I am able to transfer the object from my Laravel blade to the Vue.js component and view it in the console, I encounter an error when a ...

The module in the relative path cannot be located by Node.js

Node.js is giving me some trouble with exporting and importing classes from multiple files. In one file, I have two classes that I'm exporting using the following code: module.exports = {TrigInter, Hilbert}; However, when I try to import these classe ...

Incorporating FaceBook into a PhoneGap Application

Currently, I am working on integrating Facebook into my phonegap/cordova application. To guide me through the process, I am using the resources provided in this link: https://github.com/davejohnson/phonegap-plugin-facebook-connect/ Even though I have bee ...

Conceal the slider thumb within the material-ui framework

I've been attempting to conceal the slide thumb, initially without using a library. However, I started considering utilizing material-ui as it might make the process easier. Hence, I'm seeking assistance here. Below is my code snippet: import * ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...

There seems to be a syntax error near the comma when executing the update query

Here is the code snippet that I have implemented in my website. However, I am encountering an error stating "Incorrect syntax near ','". Can someone please help me identify the issue in the code? protected void btnadd_Click(object sender, EventA ...

Conceal one element and reveal a different one upon submitting a form

On a web page, I want to hide the form upon submission (either by clicking or pressing enter) and display the results. However, this functionality does not seem to work when the Go web server is running. When I test the HTML file (without executing the Go ...

Guide on adding Russian characters into a SQL Server database table

While attempting to insert Russian characters into an SQL table with a data type of Nvarchar(max), I encountered an issue. After inserting the Russian value "Македонски", the table values turned into "??????????". Unfortunately, I am unable to m ...