2017-01-29 22 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); 
}); 
相關問題