简体   繁体   中英

disable enable button using jquery

I have a working javascript version to disable/enable a from button but I can not get it working using jQuery.

My jsfiddle has both versions. The javascript version is commented out.

    //NOT WORKING jQuery
   function controls(id) {
   if (id === "button_start") {
    //$('button_start').prop('disabled','disabled');
    // $('button_stop').removeProp('disabled','disabled');

    // testing
    $('#button_start').on('click',function() {
        $(this).prop('disabled', 'disabled');
    });
    $('#button_stop').on('click', function(){
        $(this).removeProp('disabled', 'disabled');
    });

    //console.log(id);

   } else {
    //$('button_stop').prop('disabled','disabled');
    //$('button_start').removeProp('disabled','disabled');

     // testing
    $('#button_stop').click(function() {
        $(this).prop('disabled', 'disabled');
    });
    $('#button_start').click(function(){
        $(this).removeProp('disabled', 'disabled');
    });
      //console.log(id);
        }
    }

jsFiddle: https://jsfiddle.net/tommy6s/w2u8eskv/

Thank you for your help!

This might not solve your problem, however you are using the removeProp method wrong. According to the jQuery documentation, removeProp takes only one attribute

.removeProp( propertyName )
propertyName
Type: String
The name of the property to remove.

In your example, I would change your lines that look like this

$('#button_start').click(function(){
    $(this).removeProp('disabled', 'disabled');
});

to this

$('#button_start').click(function(){
    $(this).removeProp('disabled');
});

https://api.jquery.com/removeProp/

Also, remember that id elements must start with the # sign. You had that in your OP but not in the fiddle.

Your selectors are wrong.

$('button_start')

should be

$('#button_start') 
   ^--------------- Missing id selector syntax

Then you need to include the jQuery library for the fiddle to start working.

Add the style:

#button_start:disabled{background:blue;opacity:0.3;}

and your script:

function controls(id) {

    if (id === "button_start") {
        $('#button_start').attr('disabled','disabled');      
        $('#button_stop').removeProp('disabled');
    } else {
        $('#button_stop').attr('disabled','disabled');
        $('#button_start').removeProp('disabled');
    }
}

For jQuery versions after 1.6:

$('#button_start').prop('disabled', false); //to enable and pass true to disable

For other options and versions, look at this SO answer Disabling and enabling an HTML input button

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM