stop label from toggling the input checkbox

后端 未结 5 1386
生来不讨喜
生来不讨喜 2021-01-17 09:34

I have the following html code. When clicking on the label it toggles the checkbox.

相关标签:
5条回答
  • 2021-01-17 10:26

    The best solution would be to let label toggle the checkbox as that is intuitive and expected behaviour.

    Second best solution is to make sure your checkbox is not nested inside label and label does not have for attribute. If you have some logic that depends on it, you can put data attributes on elements and use those in your logic.

    <input type="checkbox" data-myid="1" />
    <label data-myid="1">foo</label>

    Last resort

    You could prevent the default behaviour of the click event using jQuery:

    $('label[for="startClientFromWebEnabled"]').click(function(e) { 
        e.preventDefault();
    });​
    

    Please see this jsFiddle for an example.

    0 讨论(0)
  • 2021-01-17 10:27

    There is CSS solution too:

    label {
       pointer-events: none;
       cursor: default;
    }
    
    0 讨论(0)
  • 2021-01-17 10:31

    if you are using JQuery, add an id on your label then add this in your script:

    $("#lbl").click(function(){
       return false; 
    });
    
    0 讨论(0)
  • 2021-01-17 10:39

    "I have some logic that takes the id from the element "

    You could remove the for-attribute, if you store the ID somewhere else. For example in a data-*-attribute:

    <label data-input-id="startClientFromWebEnabled">
    

    On the other hand, it is sometimes difficult to point and click an a check-box based on the styling and the capabilities of the user. There is are good reasons for using the for-attribute.

    0 讨论(0)
  • 2021-01-17 10:39

    Just prevent default on label or any part of label, if desired.

    document.querySelector('.prevent-default').addEventListener('click', (e)=>{
       e.preventDefault();
    }, false);
        <input type="checkbox" id="1" />
        <label class="prevent-default" for="1">foo</label>

    or

    document.querySelector('.prevent-default').addEventListener('click', (e)=>{
       e.preventDefault();
    }, false);
        <input type="checkbox" id="1" />
        <label for="1">foo some part <span class="prevent-default">not</span> clickable</label>

    0 讨论(0)
提交回复
热议问题