2011-03-24 20 views
45

我想在輸入具有「只讀」屬性時發出警報。我試過這個:輸入具有「只讀」屬性時檢測

if($('input').attr('readonly') == 'readonly'){ 

    alert("foo"); 
    } 

我覺得'如果'甚至不是最好的辦法。

回答

107

最快的方法是使用.is() jQuery函數。

if ($('input').is('[readonly]')) { } 

使用[readonly]彷彿該屬性的元素上定義的選擇器簡單地檢查。如果你想檢查一個值,你可以使用這樣的事情,而不是:

if ($('input').is('[readonly="somevalue"]')) { } 
+0

我想阻止回發,只有當它是隻讀模式。我有一個asp.net頁面。 http://stackoverflow.com/questions/30351993/how-to-disable-enter-key-when-a-asp-net-textarea-is-in-readonly-mode – SearchForKnowledge 2015-05-20 14:02:30

3

你可以使用屬性選擇,然後測試長度:

$('input[readonly]').length == 0 // --> ok 
$('input[readonly]').length > 0 // --> not ok 
0

試試這個:

if($('input').attr('readonly') == undefined){ 
    alert("foo"); 
} 

,如果它不存在這將是JS

3

檢查undefined您的「只讀」屬性的當前值,如果它是「假」(字符串)或空(未定義或「」),則它不是隻讀的。

$('input').each(function() { 
    var readonly = $(this).attr("readonly"); 
    if(readonly && readonly.toLowerCase()!=='false') { // this is readonly 
     alert('this is a read only field'); 
    } 
}); 
2

嘗試一個簡單的方法:

if($('input[readonly="readonly"]')){ 
    alert("foo"); 
} 
14

由於JQuery的1.6,一直使用.prop() 閱讀爲什麼在這裏:http://api.jquery.com/prop/

if($('input').prop('readonly')){ } 

.prop()也可以被用於設置屬性

$('input').prop('readonly',true); 

$('input').prop('readonly',false);