allenhe
allenhe

Reputation: 81

disable label click event

I am trying to create radio button and labels in one div called Contentarea. the problem I am having right now is both radio button and label are clickable, anyone would please tell me how can I disable the click event of label in the following code.

<div id="ContentArea" class="contentarea">  </div>
$("#ContentArea").click(function(evt) {
    $("#ContentArea").empty();
    $("#lblarea").empty();
    $("#btngroup").empty();
    var clicked = evt.target;
    var currentID = clicked.id || "No ID!";
    var type = clicked.value;
    if (type == "button") {
        loadlabelpagebyID(currentID);
    } else if (type == "raidobutton") {
        loadlabelpagebyID(currentID);
    };
});

function loadradiobuttonpagebyID(pageid) {
    $.get("HeadachePROData.xml", function(xml) {
        $(xml).find('Pages').each(function() {
            $(xml).find('Page[id="' + pageid + '"]').each(function(i) {
                pagetype = $(this).attr("type");
                nextpageid = $(this).attr("nextpage");
                backpageid = $(this).attr("backpage");
                sessionStorage.setItem("nextpageid", nextpageid);
                sessionStorage.setItem("backpageid", backpageid);
                $(this).find('nav').each(function(i) {
                    var btntext = $(this).text();
                    navpageid = $(this).attr("navpage");
                    navtype = $(this).attr("type");
                    var testbtn = $('<input type="radio">', {
                        value: navtype,
                        id: navpageid
                    });
                    var $radiolabel = $("<label>").text(btntext);
                    $radiolabel.removeAttr('onclick').off('click');
                    $("#ContentArea").append(testbtn);
                    $("#ContentArea").append($radiolabel);
                    $("#ContentArea").append("<br/><br/>");
                });
            });
        });
    });
}

Upvotes: 8

Views: 25195

Answers (2)

jfxninja
jfxninja

Reputation: 381

This can also be achieved with just css though please take note, browser support is limited in IE:

label {
    pointer-events:none;
}

Browser support https://caniuse.com/#feat=pointer-events

Upvotes: 15

Joseph Marikle
Joseph Marikle

Reputation: 78520

It's entirely inadvisable, but you can attach a click event to the label, check that the label itself was clicked, and prevent default if that is the case. See below:

$('.cancel-click').on('click', function(e){
  if(e.target.nodeName === 'LABEL') e.preventDefault();
});
/* just demo styles */
label {
  float:left;
  clear:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox"> Clickable Label</label>
<label class="cancel-click"><input type="checkbox"> Non-Clickable Label</label>

Upvotes: 7

Related Questions