MaskedEditExtender Is Too Hard to Use For Money

Zack Peterson picture Zack Peterson · Sep 25, 2009 · Viewed 8.6k times · Source

The MaskedEditExtender does a good job of enforcing the rules, but my users have trouble typing into its TextBox.

I want to select all the contents of my TextBox when it gains focus.

A regular JavaScript solution does not work.

onfocus="javascript:this.select();"

The MaskedEditExtender interferes.

How can I select all the contents of the TextBox when it gains focus?

<asp:TextBox
    ID="TextBoxPrice"
    runat="server" />
<ajaxToolkit:MaskedEditExtender
    ID="MaskedEditExtenderTextBoxPrice"
    runat="server"
    TargetControlID="TextBoxPrice"
    Mask="9,999.99"
    MaskType="Number"
    MessageValidatorTip="False"
    OnFocusCssClass="MaskedEditFocus"
    OnInvalidCssClass="MaskedEditError"
    InputDirection="RightToLeft"
    AcceptNegative="None"
    DisplayMoney="Left" />
<ajaxToolkit:MaskedEditValidator
    ID="MaskedEditValidatorTextBoxPrice"
    runat="server"
    ControlToValidate="TextBoxPrice"
    ControlExtender="MaskedEditExtenderTextBoxPrice"
    Display="Dynamic"
    IsValidEmpty="False"
    EmptyValueMessage="Price is required"
    InvalidValueMessage="Price is invalid"
    MinimumValue= "0.01"
    MinimumValueMessage="Price is too small"
    MaximumValue="9999.99" 
    MaximumValueMessage="Price is too large" />

Answer

Antonio Sgrignoli picture Antonio Sgrignoli · May 18, 2017

use this script:

<script type="text/javascript">

        function selectAllCharsBefore(inputText, char) {


            setTimeout(function () {
                if (!inputText) return false;

                var indexChar = inputText.value.indexOf(char);
                if (indexChar != -1) createSelection(inputText, 0, indexChar)
            }, 100);


            return true;


        }

        function whatDecimalSeparator() {

            var n = 1.1;

            n = n.toLocaleString().substring(1, 2);

            return n;

        }

        function createSelection(field, start, end) {
            if (field.createTextRange) {
                var selRange = field.createTextRange();
                selRange.collapse(true);
                selRange.moveStart('character', start);
                selRange.moveEnd('character', end);
                selRange.select();
                field.focus();
            } else if (field.setSelectionRange) {
                field.focus();
                field.setSelectionRange(start, end);
            } else if (typeof field.selectionStart != 'undefined') {
                field.selectionStart = start;
                field.selectionEnd = end;
                field.focus();
            }
        }


    </script>