vendredi 26 février 2016

auto delete new characters javascript

I'm working on a lab for school, and the goal is to create a web control to will only accept a monetary value from the user.

Rules:
1st digit must be “-“ or “$”
2nd digit must be “$” or a number
3rd digit on must be a number or a “.”
Only two digits after decimal
Must have a “$”

The problem I'm having, is that while I can set up labels to display when something is or is not allowed, I can't figure out how to get it to auto delete new characters when the conditions haven't been met. (E.G. can't enter "-1", only "-$" or "$1".) Trying to set the substring's length doesn't seem to be working. The condition in the current example also only seems to work when the string consists only of "-". Any extra characters added do not trigger it.

Code:

    function text2money(e) {
        // get value of txt
        var str = document.getElementById("<%=txt.ClientID %>").value;

        if (str.substring(0, str.length) === "-" && str.substring(1, str.length) !== "$") {
                str.length = 2;
        }

        // goes through string one character at a time, converts them to char, then checks if char is a decimal digit
        if (str.substring(0, 1) === ('-') || str.substring(0, 1) === ('$')) {
            document.getElementById("<%= lbl1.ClientID %>").innerHTML = "True"; // must use .innerHTML with labels

            // check if second digit is '$' or numeric
            if (str.substring(1, 2) === ("$") || isFinite(str.substring(1, 2))) {
                document.getElementById("<%= lbl1.ClientID %>").innerHTML = "It's numeric";

                // check if third and any future characters are '.' or numeric

            } // end second char if

            else {
                document.getElementById("<%= lbl1.ClientID %>").innerHTML = "Second char must be '$' or numeric";
            } // end second char

        } // end first char if
        else {
            document.getElementById("<%= lbl1.ClientID %>").innerHTML = "First character must be '-' or '$'";
        } // end first char

        // check if $ is included anywhere in the string
        var result = str.indexOf("$") <= -1; // -1 == false
        if (result) {
            document.getElementById("<%= lbl2.ClientID %>").innerHTML = "$ is a required character";
            }
            else {
                document.getElementById("<%= lbl2.ClientID %>").innerHTML = "";
            }

        } // end text2money

Aucun commentaire:

Enregistrer un commentaire