簡體   English   中英

如何使用jQuery單擊禁用/啟用輸入字段

[英]How to disable/enable input field on click with jQuery

如何使用jQuery正確啟用/禁用點擊輸入字段?

我正在嘗試:

$("#FullName").removeAttr('disabled');

從此輸入字段中刪除disabled="disabled"

<input id="FullName" style="width: 299px" value="Marko" disabled="disabled" />

但是如何通過單擊另一個按鈕再次添加它或如何在單擊時禁用輸入字段?

對於jQuery版本1.6+使用prop

$('#elementId').click(function(){
        $('#FullName').prop('disabled', true\false);
});

對於舊版本的jQuery,請使用attr

$('#elementId').click(function(){
        $('#FullName').attr('disabled', 'disabled'\'');
});
$("#FullName").prop('disabled', true);

會做。

但是在禁用它之后請記住(通過上面的代碼) onclick處理程序不會作為其禁用。 要再次啟用它,請添加$("#FullName").removeAttr('disabled'); 在另一個按鈕或字段的onclick處理程序中。

$('#checkbox-id').click(function()
{
    //If checkbox is checked then disable or enable input
    if ($(this).is(':checked'))
    {
        $("#to-enable-input").removeAttr("disabled"); 
        $("#to-disable-input").attr("disabled","disabled");
    }
    //If checkbox is unchecked then disable or enable input
    else
    {
        $("#to-enable-input").removeAttr("disabled"); 
        $("#to-disable-input").attr("disabled","disabled");
    }
});

啟用/禁用輸入場的另一種簡單方法

 $("#anOtherButton").click(function() { $("#FullName").attr('disabled', !$("#FullName").attr('disabled')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <input id="FullName" style="width: 299px" value="Marko" disabled="disabled" /> <br> <br> <input type="button" id="anOtherButton" value="disable/enable" /> 

這應該做到這一點。

$("#FullName").attr('disabled', 'disabled');

Shiplu是正確的,但是如果你沒有使用jquery 1.6+,請使用它

$("#anOtherButton").click(function(){
  $("#FullName").attr('disabled', 'disabled'); 
 });

要在禁用和啟用之間切換字段,請嘗試以下操作:

$('#toggle_button').click(function () {
    $('#FullName').prop("disabled",

    function (i, val) {
        return !val;
    });
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM