2012-11-07 23 views
4

jQuery的按鈕來添加/刪除禁用屬性:無法根據複選框選中屬性

<script type="text/javascript"> 

function enableDisableButton() { 

    var isChecked = ($('input[name=ignore-checkbox]').is(':checked')); 

    if (isChecked == true) { 
     $("button[name=set-up-account]").removeAttr("disabled"); 
    } 
    else { 
     $("button[name=set-up-account]").attr("disabled", "disabled"); 
    } 

} 

$('#mobilePage').live('pageinit', function (event) { //document ready for jquery mobile 

    enableDisableButton(); 

    $('#ignore-checkbox').bind("change", function() { 
     enableDisableButton(); 
    }); 

}); 
    </script> 

HTML:

@using (Html.BeginForm("Account", "SetUpAccount", FormMethod.Post, new { @id = "account-set-up", @data_ajax = "false" })) 
{  

    <div class="ui-grid-a field"> 
     <div class="ui-block-a" style="width:140px;"> 
     <label for="ignore-checkbox">Ignore</label> 
     <input type="checkbox" name="ignore-checkbox" id="ignore-checkbox"/> 
     </div> 
    </div> 

    <div style="width:100%;float:left;"> 
     <button type="submit" name="set-up-account" id="set-up-account" data-inline="true" data-mini="true">Set Up Account</button> 
    </div> 
    } 

我想啓用/基於複選框禁用Set Up Account按鈕選中屬性。如果複選框被選中,則啓用按鈕,否則禁用。在頁面加載我正在禁用按鈕

我現在面臨的問題是,

在頁面加載,它禁用按鈕,但基於複選框的更改事件它不是添加/刪除disabled屬性,我檢查螢火蟲,它根據檢查和未檢查的值正確進入循環。

注意:我正在使用Jquery mobile 1.2和jquery 1.7。另外在發佈之前,我在谷歌搜索,有很多張貼下啓用和禁用基於複選框選中的值的按鈕。但沒有解決我的問題。

有什麼問題?請幫我

謝謝...

+0

您的代碼正常工作,請參閱此處演示:http://jsfiddle.net/dwzGf/2/':)'點擊複選框,您將看到啓用和禁用按鈕 –

+0

但是在我的頁面中,關於檢查複選框的禁用屬性,其可能是因爲jquery mobile? – Subha

+0

試試這個 - 小改動:http:// jsfiddle。net/26n4M/1 /而不是'(isChecked == true)'只需要執行'(isChecked)',它應該在JQ M'中運行:'' –

回答

6

它不能夠因爲jQuery移動的按鈕。在JQM,我們需要刷新表單元素,而操縱它

的解決方案是

function enableDisableButton() { 

    var isChecked = ($('input[name=ignore-checkbox]').is(':checked')); 

    if (isChecked) { 
     $("button[name='set-up-account']").removeAttr("disabled").button('refresh'); 
    } 
    else { 
     $("button[name='set-up-account']").attr("disabled", "disabled").button('refresh'); 
    } 
} 

$('#mobilePage').live('pageinit', function (event) { 

    enableDisableButton(); 

    $('#ignore-checkbox').bind("change", function() { 
     enableDisableButton(); 
    }); 
}); 

的問題,通過加入

.button('refresh'); 
0

試試這個

$("input[name=ignore-checkbox]").click(function() { 
    $("button[name=set-up-account]").attr("disabled", this.checked); 
}); 

DEMO

+0

你試過這個嗎? – 2619

+0

是的嘗試過,它觸發點擊事件,但沒有啓用按鈕 – Subha

+0

你檢查過演示嗎?它的啓用和禁用按鈕,當你選中或取消選中複選框 – 2619

3

贊一個

$('#setagb').change(function(){ 
     if ($(this).is(':checked')) 
     { 
      $("#submit").removeAttr("disabled"); 
     } 
     else 
     { 
      $("#submit").attr("disabled", "disabled"); 
     }    
    }); 
18
解決

我不確定這是否有助於解決您的主要問題,但根據http://api.jquery.com/prop/您應該使用.prop()函數添加和刪除禁用的屬性,而不是.attr()和.removeAttr()函數。

添加屬性:

.prop("disabled", true); 

要刪除屬性:

.prop("disabled", false); 

我碰到這個問題絆倒在尋找上述信息,所以我想我會分享。

+2

對於其他人想知道的,這是正確的答案。 – JMac