Search code examples
javascriptjqueryhtmljquery-uijquery-dialog

how to remove and add back OR bind and unbind a click event in Jquery


I want to enable and disable a click event for Jquery Dialog box, so if the user click "Link #1", the dialog box open once and on close it should disable the "Link #1", and the link should not open the Dialog Box unless the user clicks on "Link #2"

I tried jquery using .unbind() method, but it doesn't enable my button 1st link. it permanently disable the click event.

Or is there any other method with "Jquery UI Dialog" which allows to not to open the Dialog Box?

Here is my code:

HTML

    <span title="Accept" class="Accepted">Accept</span>
    <span title="Reject" class="Rejected">Reject</span>

JQUERY

    $(".Accepted").click(aceeptMethod);
        $(".Rejected").click(function () {
            $(this).closest('.rx-container').addClass('selected');
            $("#rejectReason").dialog("open");
        });

    $("#rejectReason").dialog({
            autoOpen: false,
            modal: true,
            buttons: {
                "Submit": function () {
                    $(this).dialog("close");
                    rejectMethod();
                },
                    "Cancel": function () {
                    $(this).dialog("close");
                }
            }
        });

       function aceeptMethod() {
            var $parent = $(this).closest('.rx-container');

            $(this).next().bind('click'); // BINDING BACK THE CLICK EVENT
            $('.rx-statusRejected', $parent).hide();
            $('.rx-statusAccepted', $parent).show();
            $('.rejectReasonBox', $parent).hide();
        }

        function rejectMethod() {
            $('.selected .rx-statusRejected').show();
            $(".selected .rx-statusAccepted").hide();
            $(".selected .rejectReasonBox").show();
            $('.selected .Rejected').unbind('click'); // UNBINDING THE CLICK EVENT
        }

Here is the Fiddle to show how my code is working: http://jsfiddle.net/aasthatuteja/W97wP/

Please Suggest!


Solution

  • If you change your links to input elements then you can use the disabled property. If you want to unbind and then bind the click event back you will need to re-call all the code inside the new click event that you called in the original click event.

    Also your not targeting the rejected span with the following code. Your targeting the <br> tag.

    $(this).next().bind('click'); 
    

    You can try sibliings function like this.

    $(this).siblings(".Rejected").bind('click');
    

    Re-bind with the original code.

      $(this).siblings(".Rejected").bind('click',function () {
          $(this).closest('.rx-container').addClass('selected');
          $("#rejectReason").dialog("open");
      });