KeyPress和Keydown没有处理这个特定的代码。只有密钥才起作用

时间:2015-04-07 05:56:01

标签: javascript

代码应该只允许数字而不允许文本框中的特殊字符和符号以及字符。但是keypress和keydown函数在此代码中不起作用。它还会阻止数字进入文本框。

function radioValidation() {
    var x = document.exform.tags;
    var numbers = /^[0-9]+$/;
    var namepattern = /^[a-zA-Z\s]+$/;
    var letters = /^[0-9a-zA-Z-]+$/;
    var radioId = $('input:checked').val();
    if (radioId == "mobileno") {
        x.maxLength = "11";
        if (!numbers.test(x.value)) {
            x.value = "";
            document.getElementById('chose').innerHTML = "Numbers only";
            x.focus();
            return false;
        }
        document.getElementById('chose').innerHTML = "";
    } else if (radioId == "firstname") {
        x.maxLength = "50";
        if (!namepattern.test(x.value)) {
            x.value = "";
            document.getElementById('chose').innerHTML = "Enter only               alphabets.";
            x.focus();
            return false;
        }
        document.getElementById('chose').innerHTML = "";
    } else {
        x.maxLength = "15";
        if (!letters.test(x.value)) {
            x.value = "";
            document.getElementById('chose').innerHTML = "No specail charecters";
            x.focus();
            return false;
        }
        document.getElementById('chose').innerHTML = "";
    }
    return true;
}


<input type="text" name="tags" id="tags" size="35px;"
                                class="form-control" onkeypress="return radioValidation()">
<label id="chose" style="color: red; width: 150px;"></label>

2 个答案:

答案 0 :(得分:0)

如果您只想要数字。

function numbersOnly(params){
    return params && !isNaN(params) ? true:false;
}

因为您使用jquery实际上可以

$(".form-control").on("keyup",function(){
    var whatyouwilldo = numbersOnly($('input:checked').val());
}

你可以玩whatyouwilldo变量:)

答案 1 :(得分:0)

使用onkeyup()代替keypress()

HTML

<input type="text" name="tags" id="tags" size="35px;"
                                class="form-control" onkeyup="return radioValidation()">
<label id="chose" style="color: red; width: 150px;"></label>

的Javascript

function radioValidation() {

    var x = document.getElementById("tags");    

    var numbers = /^[0-9]+$/;
    var namepattern = /^[a-zA-Z\s]+$/;
    var letters = /^[0-9a-zA-Z-]+$/;

        if (!numbers.test(x.value)) {
            x.value = "";
            document.getElementById('chose').innerHTML = "Numbers only";
            x.focus();
            return false;
        }

    return true;
}

Fiddle