Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining an <a> tag and a <label>

Tags:

html

I can't make a and an tag combine on HTML. I'm trying to have text that when you click on it both click a checkbox and also lead you somewhere on the page i've tried to make it like that:

<a href"#somewhere"><label for"somecheckbox">Some Text</label></a>

But only the label worked, then I tried it like that:

<label for"somecheckbox"><a href"#somewhere">Some Text</a></label>

But then only the link works, is there any way in which we can use both?

like image 490
Eliav Cohen Avatar asked Dec 20 '25 21:12

Eliav Cohen


2 Answers

The problem is you are trying to nest interactive content. This is something you can't do via the W3C spec. See the a tag, for instance with it's permitted content.

You will need to use javascript to achieve what you want to do.

Here is a quick example:

var links = document.querySelectorAll("[data-for]");

//Set Event Handler
for(var i = 0; i < links.length; i++) {
  links[i].addEventListener("click", function(event){
    //Get the target cb from the data attribute
    var cbTarget = this.dataset.for;
    //Check the cb
    document.getElementById(cbTarget).checked = true;
  });
}
.head {margin-bottom: 100vh;}
<div class="head">
<a href="#aTarget" data-for="aCheckBox">Click Me</a> <input type="checkbox" id="aCheckBox" />
</div>
<div id="aTarget">A Target</div>
like image 116
Jon P Avatar answered Dec 23 '25 10:12

Jon P


It's not possible to do both navigation and toggle checkbox using tags, please use javascript to focus on target when checkbox is checked.

document.getElementById("somecheckbox").addEventListener("change", function(e){
  // see if it is checked
  if(e.target.checked){
    // and focus to specific id
    document.getElementById("somewhere").focus();
  }
})
like image 24
bhansa Avatar answered Dec 23 '25 09:12

bhansa