用于编辑的按钮文本

时间:2018-01-24 08:31:15

标签: javascript html5

我有一个HTML按钮,我希望用户在其上编辑文本,并仅在按下按钮时将其限制为5位数和数字。如果用户输入除数字以外的内容,请取消编辑并返回原始数字。

我为按钮编写了以下HTML:

<button id='altitudeBtn' type='button' class='btn btn-default' contenteditable="true" onkeypress="validateNumber()" onclick="altBtnPressed()">

JS:

function altBtnPressed(){
    previousAltitude = document.getElementById('altitudeBtn').innerHTML;
    document.getElementById('altitudeBtn').innerHTML = '';
    altBtnPressedBool = true;
}

function validateNumber(event) {
    if(altBtnPressedBool){
        var key = window.event ? event.keyCode : event.which;
        if (event.keyCode === 8 || event.keyCode === 46) {
            return;
        } else if ( key < 48 || key > 57 ) {
            //return false;
            document.getElementById('altitudeBtn').innerHTML = previousAltitude;
        } else {
            //code for correct input;
        }
    }
}

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

这应该做的伎俩

} else {
    //code for correct input;
    if(document.getElementById('altitudeBtn').innerHTML.Length <= 4) {
        document.getElementById('altitudeBtn').innerHTML =
        document.getElementById('altitudeBtn').innerHTML + String.fromCharCode(key);
    }
}

答案 1 :(得分:0)

解决:

function validateNumber(event) {
if(altBtnPressedBool){
    var key = window.event ? event.keyCode : event.which;
    if (event.keyCode === 8 || event.keyCode === 46) {
        return true;
    } else if ( key < 48 || key > 57 ) {
        return false;
        //document.getElementById('altitudeBtn').innerHTML = previousAltitude;
    } else {
        return (document.getElementById('altitudeBtn').innerHTML.length <= 4);
    }
}

}