簡體   English   中英

如果啟用了復選框,則不會啟用按鈕

[英]button is not being enabled if checkbox is on

我只想在復選框打開時啟用按鈕。 我在這做錯了什么? 提前致謝..

的index.html

<p><input id="agree" type="checkbox" /> I agree</p>
<input id="continue" value="continue" type="button" disabled="disabled" />

custom.js

$( document ).ready(function () {
    $('#agree').change(function () {
        var state = $(this).attr('value');

        if (state == 'on') {
            $('#continue').removeAttr('disabled')
        } else if (state == '') {
            $('#continue').attr('disabled','disabled');
        }
    });
});

您可以將其簡化為以下內容:

這里的例子

$('#agree').on('change', function () {
    $('#continue').attr('disabled', !this.checked);
});

 $('#agree').on('change', function () { $('#continue').attr('disabled', !this.checked); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p><input id="agree" type="checkbox" />I agree</p> <input id="continue" value="continue" type="button" disabled="disabled" /> 

您的代碼無法正常工作的原因是因為您使用的是.attr() 由於沒有value屬性,因此需要使用.prop() 這仍然不會工作,雖然,因為該值將始終返回on 你需要讓checked屬性訪問this.checked.prop('checked') - 使用原始代碼片段的工作示例

$('#agree').on('change', function () {
    if (this.checked) {
        $('#continue').removeAttr('disabled')
    } else {
        $('#continue').attr('disabled', 'disabled');
    }
});

嘗試這個:

$( document ).ready(function() {

  $('#agree').change(function() {
        if(this.checked) {
            $('#continue').removeAttr('disabled')
        } else {
            $('#continue').attr('disabled','disabled');
        }
    });

});    

如果要檢查輸入是否已檢查:

 state = $(this).prop( "checked" );

這將返回布爾值(如果選中則返回true;如果未選中則返回false)。

暫無
暫無

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

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