How to use a mask in a dynamic textbox?

Asked

Viewed 43 times

0

I need to implement a mask (value) in n Textbox fields (defined by n periods x n contracts) within a grid, where they are generated dynamically. I use jQuery for static textboxes (Autonumeric). But I don’t know how to reference them dynamically, since I need Clientid for autonumeric to work.

Excerpt from the script that uses autoNumeric in a Static Textbox: (.aspx)

$("#<%=txtValor.ClientID%>").autoNumeric({ aSep: '.', aDec: ',' });

Method in code-Behind in which Gero a dynamic textbox (.Cs):

private TextBox geraTextBox(string periodo, string linha)
    {
        TextBox textBox = new TextBox();
        textBox.ID = periodo + "_" + linha;
        textBox.Width = 50;
        textBox.AutoPostBack = true;
        textBox.TextChanged += new EventHandler(txtBoxes_TextChanged);
        textBox.ReadOnly = false;
        return textBox;
    }

Note: I apologize for any syntax/user error of Stack Overflow. This is the first time I ask a question.

  • The most correct way would be to create a new control and implement the interface IScriptControl. Take a look at this link. It is in VB, but in general it is the same thing. You can also add an attribute in the textbox, which implements the load method of javascript.

  • I will use the first strategy and then pass the result

1 answer

0


I ended up leaving the IScriptControl aside, because with the amount of Textboxes that would handle, would imply a very time consuming return. I used the second option, in Javascript. Within the RowDataBound added an attribute that implemented the mask. I passed the clientID by parameter, and javascript did the rest. Below is the solution:

Server-Side (.Cs):

protected void gdvCriarProjeto_RowDataBound(object sender, GridViewRowEventArgs e)
{
    (...)
    var txt = e.Row.FindControl(periodo + "_" + linha) as TextBox;
    txt.Attributes.Add("onClick", "javascript:Moeda(\"" + txt.ClientID + "\")");
    (...)
}

Client-Side (.aspx)

<script type="text/javascript">
    function Moeda(id_textbox) {
        var campo = document.getElementById(id_textbox);
        $(campo).autoNumeric({ aSep: '.', aDec: ',' });      
    }
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.