2016-02-13 129 views
0

我有這個問題。我的用戶可以點擊一個-按鈕從總數中減去1。他們不能低於0。當我點擊我的按鈕到0,然後點擊+按鈕,可以在0以上工作。但是,當我想再次點擊-按鈕時,它仍然被禁用。如何啓用禁用按鈕jquery

這裏是我的代碼

$('#minderApple').click(function(){ 
    $("#appletotal").val(parseInt($("#appletotal").val()) - 1); 
    if ($('#appletotal').val() < 1){ 
     $("#minderApple").prop("disabled",true); 
    }else{ 
     $("#minderApple").prop("disabled",false); 
    } 
}); 

回答

0

的問題是因爲val()返回一個字符串,你比較爲整數。您可以使用parseInt()將該值轉換爲int。另外,您可以通過直接向prop()提供布爾值來刪除if語句。試試這個:

$('#minderApple').click(function() { 
    var $appleTotal = $('#appletotal'); 
    var newVal = parseInt($appleTotal.val(), 10) - 1; 
    $appleTotal.val(newVal); 
    $(this).prop("disabled", newVal < 1); 
}); 

Working example

+0

並不能解決問題 – Wesley

+0

這不是一個有用的迴應。你沒有得到什麼行爲?你會得到什麼樣的行爲?控制檯中有任何錯誤?如果你點擊 - 按鈕確定它的工作原理,看到你的HTML也會有很大幫助 –

+0

。但是當你在輸入欄中輸入5並點擊 - 按鈕時,它不再起作用 – Wesley

0
$('#minderApple').click(function(){ 
    if ((parseInt($("#appletotal").val()) - 1) < 1){ 
     $("#minderApple").attr("disabled","disabled"); 
    }else{ 
     $("#minderApple").removeAttr("disabled"); 
    } 
}); 
+0

你還在比較字符串:int:'if($('#appletotal').val()<1)' –

+0

這並不能解決它 – Wesley

0
<html> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
     <style> 

      .active { 
       color:red; 
      } 
     </style> 
    <script> 

     $(document).ready(function() { 

      $('#minderApple').click(function() { 
       $("#appletotal").val(parseInt($("#appletotal").val()) - 1); 
       if ($('#appletotal').val() < 1) { 
        $("#minderApple").prop("disabled", true); 
       } else { 
        $("#minderApple").prop("disabled", false); 
       } 
      }); 


      $('#plus').click(function() { 
       $("#appletotal").val(parseInt($("#appletotal").val()) + 1); 
       if ($('#appletotal').val() >1) { 
        $("#minderApple").prop("disabled", false); 
       } else { 
        $("#minderApple").prop("disabled", false); 
       } 
      }); 

     }); 
    </script> 
    </head> 

    <body> 
     <input type="text" id="appletotal" value="5"/> 
     <input type="button" id="minderApple" value="-"/> 
     <input type="button" id="plus" value="+"/> 

    </body> 

    </html>