Detect when input has a 'readonly' attribute

后端 未结 8 1171
感动是毒
感动是毒 2021-02-04 23:12

I want to throw an alert when an input has a \'readonly\' attribute. I have tried this:

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

    alert(\"foo\"         


        
相关标签:
8条回答
  • 2021-02-04 23:49

    fastest way is to use the .is() jQuery function.

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

    using [readonly] as a selector simply checks if the attribute is defined on your element. if you want to check for a value, you can use something like this instead:

    if ( $('input').is('[readonly="somevalue"]') ) { }
    
    0 讨论(0)
  • 2021-02-04 23:49

    try this:

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

    if it is not there it will be undefined in js

    0 讨论(0)
  • 2021-02-04 23:55

    what about javascript without jQuery ?

    for any input that you can get with or without jQuery, just :

    input.readOnly
    

    note : mind camelCase

    0 讨论(0)
  • 2021-02-05 00:01

    Check the current value of your "readonly" attribute, if it's "false" (a string) or empty (undefined or "") then it's not readonly.

    $('input').each(function() {
        var readonly = $(this).attr("readonly");
        if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
            alert('this is a read only field');
        }
    });
    
    0 讨论(0)
  • 2021-02-05 00:04

    Since JQuery 1.6, always use .prop() Read why here: http://api.jquery.com/prop/

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

    .prop() can also be used to set the property

    $('input').prop('readonly',true);
    
    $('input').prop('readonly',false);
    
    0 讨论(0)
  • 2021-02-05 00:06

    In vanilla/pure javascript you can check as following -

    var field = document.querySelector("input[name='fieldName']");
    if(field.readOnly){
     alert("foo");
    }
    
    0 讨论(0)
提交回复
热议问题