good_evening
good_evening

Reputation: 21759

How to make button unclickable after it is being clicked?

I want that after my button is clicked, it would be unclickable for a few seconds, how can I do it? I want to write a code for all buttons, not just for a one. So, I need something like that:

$(document).ready(function() {      
    $('input[type="button"]').click(function() {
        $(this).css("hidden: true");
        delay(3);
        $(this).css("hidden: normal");
    })    
})

It is just a pseudo-code, could you give me a hand?

Upvotes: 6

Views: 40583

Answers (5)

alex
alex

Reputation: 490657

With jQuery...

$(document).ready(function() {      
    $('input[type="button"]').click(function() {
        var input = this;
        input.disabled = true;
        setTimeout(function() {
           input.disabled = false;
        }, 3000);

    });    
});

jsFiddle.

Without jQuery...

document.addEventListener('DOMContentLoaded', () => {      
    document.querySelectorAll('input[type="button"]')
    .addEventListener('click', (e) => {
        let input = e.target;
        input.disabled = true;
        setTimeout(function() {
           input.disabled = false;
        }, 3000);

    });    
});

Alternatively capture the clicks on a persistent ancestor element and check if they're input[type="button"] types. This prevents attaching multiple events for each element.

Upvotes: 10

Jon
Jon

Reputation: 437904

Disabling an element is done by adding the disabled attribute, giving it the value disabled. Enabling it again is done by removing the attribute.

Update: Fixed the answer by using setTimeout -- sorry for the confusion with $.delay.

$(document).ready(function() {      
    $('input[type="button"]').click(function() {
        var el = $(this);
        el.attr('disabled', 'disabled');
        setTimeout(function() { el.removeAttr('disabled'); }, 3000);
    })    
})

Upvotes: 4

ezmilhouse
ezmilhouse

Reputation: 9131

Fiddle here: http://jsfiddle.net/ezmilhouse/Hw6Gf/1/

$(document).ready(function() {      
    $('input[type="button"]').click(function() {
        $(this).attr('disabled','disabled');
        setTimeout(function() {
           $('input[type="button"]').removeAttr('disabled');
        }, 3000);

    });    
});

Upvotes: 0

netbrain
netbrain

Reputation: 9304

This should do it.

$(document).ready(function() {      
    $('input[type="button"]').click(function() {
        $(this).hide().delay(3000).show();
    })    
})

Upvotes: 0

Marwelln
Marwelln

Reputation: 29433

Add the disabled attribute.

$(this).attr('disabled', true);

Upvotes: 6

Related Questions