Search code examples
javascriptjqueryhtmldisabled-input

Disabling the OnClick in a nested Div programmatically with Javascript/JQuery


I have a Javascript application which allows users to enable/disable controls at runtime. I have been successful in disabling/enabling nested inputs and buttons, but so far I have had no success in disabling an onclick event in a Div, so that the circled icon will not be selectable:

enter image description here

The generated HTML looks like:

<div id="56f81c3d-9666-4dab-8f35-d36e894f426f" class="field alert-success">
    <div class="field-name">By default I am disabled - Single Photo</div>
        <div id="56f81c3d-9666-4dab-8f35-d36e894f426fPhoto" class="clearfix" style="cursor: pointer; max-width: 100%; max-height: 100%;" onclick="ffffield.getFieldHandler('PhotoPicker').showPhotoCapture(this, '56f81c3d-9666-4dab-8f35-d36e894f426f');">
            <img class="pull-right" src="/MySite.Web/Content/device/images/chevronRight.png" style="width: 20px; position:relative; top: 7px;">
            <img class="pull-right" src="/MySite.Web/Content/device/images/[email protected]" style="width: 40px; position:relative; top: -5px;">
        </div>
    </div>
</div>.

In this snippet, it is the "onclick" that I need to disable. I am not picky - it can be disabling the pointer or the onclick.

I have tried the following attempts to make this work:

$("#56f81c3d-9666-4dab-8f35-d36e894f426f").children().off('click');

and

$("#56f81c3d-9666-4dab-8f35-d36e894f426f input").prop("disabled", true);

and

$("#"#56f81c3d-9666-4dab-8f35-d36e894f426f input").attr("disabled", true);

and

$(""#56f81c3d-9666-4dab-8f35-d36e894f426f input").attr("disabled", "disabled");

based on some other stackoverflow questions.


Solution

  • .off() can only disable event listeners that were added with .on() (or other jQuery methods, since they all call .on() internally). To remove an event listener that was added using the onclick attribute, you need to reassign the onclick property:

    $("#56f81c3d-9666-4dab-8f35-d36e894f426f").children().prop('onclick', null);