bryan
bryan

Reputation: 9399

Disabling .click() and then re-enabling it

So I am trying to make it so that once an element get's clicked, the click function won't work until my $.post is complete.

<div id="textbox_item">Click me</div>

This is what I have now but it's not working. I am assuming .prop('disabled', true) does not work for div elements. Could anyone help me out?

$("#textbox_item").click(function() {

    //don't let anyone click .textbox_item until $.post is complete
    $("#textbox_item").prop('disabled', true).text("Doing something..");

    $.post("/action", { item: "123" }).done(function( data ) { 
        $("#textbox_item").prop('disabled', false).text("Click me");        
    });

});

Upvotes: 0

Views: 75

Answers (3)

sctskw
sctskw

Reputation: 1598

Why not use the provided function by the jquery library specifically for this?

http://api.jquery.com/one/

button.one('click', function() {
     //on ajax success
     Button.one('click', func)
})

Upvotes: 0

Joris Buchou
Joris Buchou

Reputation: 128

2 problems here:

  • You try to use a button property on a div which won't work. HTML Disable property does not apply to divs.
  • You are mixing selectors. Your Click me div has a class textbox_item but your call $("#textbox_item") is looking for something with textbox_item as id not as a class. You should use $(".textbox_item") everytime you want to refer to this element.

HTML

<button class="textbox_item">Click me</button>

JS

$(".textbox_item").click(function()
    $(this).prop('disabled', true);
    $.post("/action", { item: "123" }).done(function( data ) { 
       $(".textbox_item").prop('disabled', false);
    });
});

Upvotes: 0

Hydrothermal
Hydrothermal

Reputation: 5081

Consider setting and checking .data() for a "disabled" data attribute.

$(".textbox_item").click(function() {
    //don't do anything if #textbox_item has been disabled
    if($("#textbox_item").data('disabled')) { return false; }

    //don't let anyone click .textbox_item until $.post is complete
    $("#textbox_item").data('disabled', true).text("Doing something..");

    $.post("/action", { item: "123" }).done(function( data ) { 
        $("#textbox_item").data('disabled', false).text("Click me");
    });

});

I also noticed that you seem to be mixing ID and class selectors - I don't know if this is intentional or not, but I advise double-checking to make sure you know what you're disabling and clicking on.

Upvotes: 1

Related Questions