2011-03-24 47 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);