Numeric textbox with javascript and cross browser compatible

I need to make a text box that does not allow the user to type any numeric key at all

        


// function to only allow numeric key presses in a textbox
// this doesn't stop pasting of non numeric values
function fnNumeric_only(e) {
    // deal with unicode character sets
    var unicode = e.charCode ? e.charCode : e.keyCode;

    // if the key is backspace, tab, or numeric
    if (unicode == 8 || unicode == 9 || (unicode >= 48 && unicode <= 57) || (unicode == 46 || unicode == 44)) {
        // we allow the key press
        return true;
    }
    else {
        // otherwise we don't
        return false;
    }
}

At the sametime I also need to make the counter/tally changing by the time you start typing or deleting a character from the text box. Let’s make a scenario this way e.g 3.25 is the text in your textbox and basically what we want is when the user pressing backspace and stop in “.” character, you want your function to assume it as “3” instead of “0”, you can use this function


function parseLocalNum(num) {
    return +(num.replace(",", "."));
}

I’ve also added these two function for getting and setting value of an input (e.g textbox and label) which is cross browser compatible

function getControlValue(controlName) {
    var controlValue = "";
    var hasInnerText = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;

    if (hasInnerText) {
        controlValue = document.getElementById(controlName).innerText;
    } else {
        controlValue = document.getElementById(controlName).textContent;
    }

    return controlValue;
}

function setControlValue(controlName, value) {
    var controlValue = "";
    var hasInnerText = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;

    if (hasInnerText) {
        document.getElementById(controlName).innerText = value;
    } else {
    document.getElementById(controlName).textContent = value;
    }

    return controlValue;
}

How to use getControlValue or setControlValue

    setControlValue("ctl00_ContentPlaceHolder1_lblClaimedHours", totalClaimed.toFixed(1).toLocaleString())

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s