0

How do you format a textbox inside a gridview using javascript. Here's what my gridview columns looks like:

<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>

And my javascript on formatting the textbox:

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, ",");
        }

The problem is, when I tend to add more rows, only the first textbox is formatted upon onblur and when the onblur event is triggered again the textbox gets formatted again resulting in a wrong output.

1
  • 1
    When you add more rows, as you are adding a html control (input type="text") you are adding multiple controls with the same ID. You could use a asp:Textbox and pass the ClientID to the javascript function. Commented Oct 6, 2014 at 7:42

1 Answer 1

1

Change your call to the JavaScript function to pass the textbox as a parameter. You can do this by using the this keyword.

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

Then in your function, just use the parameter instead.

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, ",");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, this works fine in formatting. Thou I still experience the problem whenever a textbox receives and loses the focus again, it reformats itself again.
yup, fixed it, just added a condition. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.