Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/90.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
设置maxlength输入JQuery失败_Jquery_Html - Fatal编程技术网

设置maxlength输入JQuery失败

设置maxlength输入JQuery失败,jquery,html,Jquery,Html,我想在用户键入时使用JQuery为输入[type='text']设置maxlength属性。因此,当输入[type='text']达到最大值时,它将不会继续 这是我的密码 $(document).ready(function(){ $('input#nama').keyup(function(){ if(check($('input#username'),5)){ e.preventDefault(); e.stopProp

我想在用户键入时使用JQuery为输入[type='text']设置maxlength属性。因此,当输入[type='text']达到最大值时,它将不会继续

这是我的密码

$(document).ready(function(){
    $('input#nama').keyup(function(){
        if(check($('input#username'),5)){
            e.preventDefault();
            e.stopPropagation();
        } else {
            $('input#username').val($(this).val());
        }
    });

    function check(text,max){
        if(text.length > 5){
           return true;
        } else {
           return false;
        }
    }
});

问题是输入[type='text']虽然已达到最大值,但仍在继续填充,因为check函数的第一个参数是string,您正在传递DOM对象。调用函数时,检查输入的传递值,而不是传递完整的对象。考虑如下:

check($('input#username').val(),5)
                         ^^^^^^ ===> //Calling function pass value 
完整代码:

$(document).ready(function(){
    $('input#nama').keyup(function(){
        if(check($('input#username').val(),5)){ //updated here
            e.preventDefault();
            e.stopPropagation();
        } else {
            $('input#username').val($(this).val());
        }
    });

    function check(text,max){
        if(text.length > 5){
            return true;
        } else {
            return false;
        }
    }
});

哦,是的。那是愚蠢的错误。我检查了字符串而不是输入[type='text']的值。非常感谢。我希望我解决了您的问题。请下一步不要使用SO发布调试帮助,直到它是必要的。你可以接受这个答案。在发布问题之前,请学习正确的调试脚本。喜欢编写脚本。很抱歉,我可以再问一个问题吗。当输入[type='text']尚未达到最大值时,它是可编辑的,但当它达到最大值时,它不再可编辑,尽管我已经清空了触发输入。你能告诉我怎么修吗?