2017-01-29 25 views
0

我需要这个功能帮助功能禁用按钮,如果给定的输入文本中不包含至少n个字符

function block_button(min){ 

    current=$(this).val().length; 
    if(current>=min){ 
     $(this).next().css('opacity','1'); 
    }else{ 
     $(this).next().css('opacity','0.5'); 
    } 
} 

$('input').keyup(function(){ 
    block_button.apply(4,this); 
}); 

功能的目的是在用户写入计数字符串的长度然后禁用或启用下面的按钮(我只改变了不透明度,所以这是一个“视觉”禁用,但它的目的)。

函数有一个参数的数字,这是启用按钮的最小字符串长度。问题是当我达到4个字符时什么也没有发生。

我该如何解决这个问题?

+0

我会用一些基本的调试启动:你不起作用,被调用?此时'min'和'current'的值是多少?使用浏览器的开发工具并设置一些断点或添加一些'console.log'。 –

+0

我刚刚证实了这一点。该函数工作,因为我改变它删除参数,并给出最小= 4。问题一定是在这里block_button.apply(4,this);但我不知道如何修复 –

回答

0

您不能直接在函数中使用$(this)。相反,你应该把它放在一个变量中,你打电话之前的功能,然后使用函数内部变量:

function block_button(min){ 
 

 
    current=$this.val().length; 
 
    if(current>=min){ 
 
     $this.next().css('opacity','1'); 
 
    }else{ 
 
     $this.next().css('opacity','0.5'); 
 
    } 
 
} 
 

 
$('input').keyup(function(){ 
 
    $this = $(this); 
 
    block_button(4); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<input type="text"> 
 
<button>Button</button>

而应该有按钮默认是关闭的,然后如果用户在输入字段中输入多于X个字符,已禁用属性被删除。如果用户随后删除字符,再次添加属性:

function disableButton(min) { 
 

 
    current = $this.val().length; 
 
    if (current >= min) { 
 
    $this.next().removeAttr("disabled"); 
 
    } else { 
 
    $this.next().attr("disabled", ""); 
 
    } 
 
} 
 

 
$('input').keyup(function() { 
 
    $this = $(this); 
 
    disableButton(4); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<input type="text"> 
 
<button disabled>Button</button>

+0

谢谢,真的很有用! –

0

https://jsfiddle.net/ugeshgupta000/5grrzdnn/1/

function block_button(elem, min){ 
    current=elem.val().length; 
    if(current>=min){ 
    elem.next().css('opacity','1'); 
    }else{ 
    elem.next().css('opacity','0.5'); 
    } 
} 

$('input').keyup(function(){ 
    block_button($(this), 4); 
}); 
相关问题