Reputation: 8568
I have the following html code. When clicking on the label it toggles the checkbox.
<td><label for="startClientFromWebEnabled">Client Launch From Web:</label></td>
<td><input type="checkbox" id="startClientFromWebEnabled" name="startClientFromWebEnabled" data-bind="checked: StartClientFromWebEnabled, enable: IsEditable" onchange="startClientFromWebToggleRequiredAttribute()" /></td>
How can I prevent this? If I remove the for="startClientFromWebEnabled"
, It stops toggling but I need this because I have some logic that takes the id from the element that fires the event ...
Upvotes: 21
Views: 28480
Reputation: 5923
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>
Upvotes: 1
Reputation: 56391
There is CSS solution too:
label {
pointer-events: none;
cursor: default;
}
Upvotes: 12
Reputation: 53198
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.
Upvotes: 23
Reputation: 29932
"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.
Upvotes: 0
Reputation: 3302
if you are using JQuery, add an id
on your label then
add this in your script:
$("#lbl").click(function(){
return false;
});
Upvotes: 1