<a> tag inside tag <label> tag not triggergbox

I need to use <a> inside the <label> . Since there are many CSS styles in our current system, they apply only to <a> . The <a> tag is not associated with any pages, but for styling / hovering.

See the code below:

 <input type="checkbox" id="my-id"> <label for="my-id"><a href="javascript:void(0)">Some text</a></label> 

But when you click on "Some text", it does not switch the status of the flag.

I tried $.preventDefault() in the <a> tag but it does not work.

What should I do to make <a> behave like a label?

+5
source share
6 answers

If you remove the href attribute from a , clicking on the text will toggle the checkbox.

 <input type="checkbox" id="my-id"> <label for="my-id"><a>Some text</a></label> 

As the HTML specification indicates :

Href attribute on a and area elements not required

+2
source

Do not use <a> just for styling. Instead, use the class on the shortcut.

 .my-link-style { /* To match the cursor style for an <a> */ cursor: pointer; /* Add more styles here */ } 
 <input type="checkbox" id="my-id" /> <label for="my-id" class="my-link-style">Some text</label> 
+2
source

Updated: this answer was provided before editing that was made that is now invalid, but I will leave it for those that may be useful


Give a anchor pointer-events: none

 label[for="my-id"] { cursor: pointer; } label[for="my-id"] a { pointer-events: none; } 
 <input type="checkbox" id="my-id"> <label for="my-id"><a href="#">Some text</a></label> 

If you need to support an old browser, use a pseudo-element to cover it

 label[for="my-id"] { cursor: pointer; position: relative; } label[for="my-id"]::after { content: ' '; position: absolute; left: 0; top: 0; right: 0; bottom: 0; } 
 <input type="checkbox" id="my-id"> <label for="my-id"><a href="#">Some text</a></label> 
+1
source

 <input type="checkbox" id="my-id"> <label for="my-id"><a href="javascript:void(0)" target="my-id">Some text</a></label> <script> document.querySelector("label[for=my-id] > a") .onclick = function(e) { var el = document.getElementById( this.parentElement.htmlFor ); el.checked = !el.checked; } </script> 
+1
source

Just place the anchor element on the outside of the label element.

 <input type="checkbox" id="my-id"> <a href="javascript:void(0)"><label for="my-id">Some text</label></a> 
+1
source

You need to reverse, include the label in:

 <input type="checkbox" id="my-id" > <a href="javascript:void(0)"><label for="my-id">Some text</label></a> 

Jsfiddle

0
source

Source: https://habr.com/ru/post/1263815/


All Articles