2009-08-06 55 views
32

提交按鈕我有一個簡單的表格,檢查通過對一個可變的用戶輸入密碼後的價值,如何禁用使用jQuery

我試圖禁用提交按鈕,做檢查,並給予警告消息,我無法弄清楚我做錯了什麼,任何幫助將不勝感激。

<form id="post_code"> 
     <input name="textfield" type="text" id="postcode" size="14" maxlength="8" /> 
     <input type="image" id="submit_postcode" src="images/B_go.png" alt="Submit Postcode" width="59" height="24" border="0" /> 
    </form> 


$(function() { 

    $('form#post_code').submit(function() { 

    var entered_post_code = $('form#post_code input#postcode').val(); 
    var post_code = "CV"; 
    if (entered_post_code == post_code) { 
     alert("post code is ok"); 
     return true; 
    }else { 
     alert("post code is not ok"); 
     return true; 
    } 
    return false; 
}); 

});

+0

http://stackoverflow.com/questions/1594952/jquery-disable-enable-submit-button – 2012-12-19 09:05:01

回答

-3
//disable 
$('#submit_postcode').attr('disabled', true); 

//re-enable 
$('#submit_postcode').removeAttr('disabled'); 
+0

嗨,是上面的代碼替換爲 $('form#post_code')。submit(function(){} 謝謝 – amir 2009-08-06 09:39:10

+2

禁用屬性應該設置爲'disabled'而不是'true' – David 2009-08-06 09:40:31

+2

David,或者工作我的朋友 – redsquare 2009-08-06 09:50:52

4
$('#submit_postcode').attr('disabled', 'disabled'); 
73

W3C的建議來設置屬性爲禁用= 「禁用」,所以:

$('#submit_postcode').attr('disabled', 'disabled'); 

重新啓用可以通過去除屬性來完成:

$('#submit_postcode').removeAttr('disabled'); 

將該屬性設置爲任何值都會導致該屬性被禁用,甚至.attr('disabled','false'),因此必須將其刪除。

+0

從jQuery 1.7開始,建議使用「.prop()」和「.removeProp()」代替attr。否則,答案仍然完美。 – Rap 2015-08-18 15:55:39

0
var entered_post_code = $('form#post_code input#postcode').val(); 
// rewrite as 
var entered_post_code = $("#post_code input[id=postcode]").val(); 

如果郵政編碼不正確,您應該返回false。沒有?

可能是你的,如果它永遠不會解決爲真,並且它總是返回false。 submit()函數的用法是正確的。

1

如果支票匹配您返回true,如果不匹配...您也返回true。 return false行永遠不會到達。

您可能想要將其中一個trues更改爲false,並刪除if/else塊之外的行。

1

這是我使用禁用或代碼重新啓用控制:

function handleControlDisplay(className, foundCount, checked) { 



    var button = jQuery(className); 



    if (foundCount > 0 && foundCount == checked) { 

     // enable 

     button.removeAttr("disabled"); 

    } 

    else { 

     // set the disabled attribute 

     button.attr("disabled", "true"); 

    }; 

}