I am trying to be able to select a parent div and have it select its respective child radio button.
Inside this parent div there is a show/hide link that shows some info in a div that's also inside this container.
Problem is when I click the show/hide link of a parent div that isn't clicked, I want it to show/hide that hidden div without selecting that div's radio button/parent div.
Looking for a clean vanilla javascript solution.
In my code so far, it's not properly selecting the parent div of radio button, and then I want to make sure the show/hide link doesn't select the div if it wasn't already selected.
HTML
<div class="box" onclick="check(this)">
<h3>This is div 1</h3>
<input id="radio1" name="field" type="radio" />
<div>
<div class="hiddenstuff">
You see me now
</div>
<p><a href="#" class="link" onclick="showhide(this)">show</a></p>
</div>
</div>
<br />
<div class="box" onclick="check(this)">
<h3>This is div 2</h3>
<input id="radio2" name="field" type="radio" />
<div>
<div class="hiddenstuff">
You see me now
</div>
<p><a href="#" class="link" onclick="showhide(this)">show</a></p>
</div>
</div>
CSS:
.box {
width: 300px;
height: 150px;
padding: 10px;
background-color: yellow;
cursor: pointer;
}
.checked {
border: 3px solid blue;
}
.hiddenstuff {
color: red;
padding: 10px;
display: none;
}
JS:
function check(box) {
var radioId = this.querySelectorAll('input[type="radio"]').value;
document.getElementById(radioId).click();
document.querySelectorAll(".box").forEach(function (item) {
item.classList.remove("checked");
});
if ((input[0].checked = true)) {
box.classList.add("checked");
}
return false;
}
function showhide(elem) {
var cont = elem.parentNode.previousElementSibling;
if (cont.style.display != "block") {
cont.style.display = "block";
elem.innerHTML = "hide";
} else {
cont.style.display = "none";
elem.innerHTML = "show";
}
return false;
elem.stopPropagation();
}
.box {
width: 300px;
height: 150px;
padding: 10px;
background-color: yellow;
cursor: pointer;
}
.checked {
border: 3px solid blue;
}
.hiddenstuff {
color: red;
padding: 10px;
display: none;
}
<div class="box" onclick="check(this)">
<h3>This is div 1</h3>
<input id="radio1" name="field" type="radio" />
<div>
<div class="hiddenstuff">
You see me now
</div>
<p><a href="#" class="link" onclick="showhide(this)">show</a></p>
</div>
</div>
<br />
<div class="box" onclick="check(this)">
<h3>This is div 2</h3>
<input id="radio2" name="field" type="radio" />
<div>
<div class="hiddenstuff">
You see me now
</div>
<p><a href="#" class="link" onclick="showhide(this)">show</a></p>
</div>
</div>