jQuery removeAttr('type') doesn't work

前端 未结 3 1711
鱼传尺愫
鱼传尺愫 2021-01-18 01:00

My problem is very simple

$(\'#button\').removeAttr(\'type\');

triggers an error on firebug

type property can\'t be changed         


        
相关标签:
3条回答
  • 2021-01-18 01:33

    Since you just want to disable the submit button:

    If you are using jQuery < 1.6 do this:

    $("#button").attr("disabled", 'disabled');
    

    If you are using jQuery 1.6+:

    $("#button").prop("disabled", true);
    

    See this question: .prop() vs .attr() for references why.

    0 讨论(0)
  • 2021-01-18 01:34

    You can't change an input's type in IE (<9?) after it has been inserted into the DOM. jQuery raises an error for all browsers because of this.

    From source:

        set: function( elem, value ) {
                // We can't allow the type property to be changed (since it causes problems in IE)
                if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
                    jQuery.error( "type property can't be changed" );
    

    There are no other cases I know about (or jQuery knows about) and how to get around this depends a lot on what you are trying to do in the first place. Consider creating a new element with different type and using that for example.

    Edit: To prevent the button from submitting a form, you can use:

    $("#button").click(function(e){
        e.preventDefault();
    });
    

    Or (credit Tim Down):

    $("#button").prop("disabled", true);
    

    To prevent form from being submitted through any means, you can use:

    $("#form").submit(function(e){
        e.preventDefault();
    });
    
    0 讨论(0)
  • 2021-01-18 01:49

    you can replace it:

    $('#button').replaceWith('<input type="text" value="text"/>');
    

    or use event.preventDefault()

    0 讨论(0)
提交回复
热议问题