2

I have a form element like this:

<div id="myformelement">
   <input type="radio" id="option1">
   <label for="option2">Option 1</label>
   <input type="radio" id="option2">
   <label for="option2">Option 2</label> 
   <input type="radio" id="option3">
   <label for="option3">Option 3</label> 
   <input type="radio" id="option4">
   <label for="option4">Option 4</label>  
</div>

I want to hide the input fields "option2" and "option3" and their labels.

I can hide the input bullets by addressing the id. Unfortunately the corresponding labels to the input fields only have a "for" tag with the id in it.

How can I do this with javascript (no jquery).

I found this question (Find html label associated with a given input), but this seems only to work with one label within an ID, I can not use this.

Thanks in advance! Kind regards, Malte

Community
  • 1
  • 1
user2092199
  • 43
  • 1
  • 3

2 Answers2

4

In pure JavaScript you can use querySelector:

document.querySelector("label[for='option2']").style.display = "none";
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 1
    +1 Absolutely, provided you don't need to support IE7 or earlier. http://caniuse.com/#feat=queryselector – T.J. Crowder Feb 20 '13 at 17:05
  • 1
    @T.J.Crowder Who cares about IE7 and earlier ;) – VisioN Feb 20 '13 at 17:06
  • @ VisioN: Really quite a large number of people in Asia, particularly China. But hey, we can all safely ignore twenty some-odd percent of 1.3 billion people, right? ;-) (Speaking seriously: Quite a few sites can [certainly all of the ones I've been involved with], if they're only in English. :-) ) – T.J. Crowder Feb 20 '13 at 17:08
  • @T.J.Crowder I guess forcing people to be updated is never bad :) – VisioN Feb 20 '13 at 17:11
  • I agreed, convincing people to use modern browsers ist high priority. Anyway, this solution also worked – user2092199 Feb 21 '13 at 10:09
2

You can do it with nextSibling:

var rdo = document.getElementById("option2");
var lbl;

rdo.style.display = "none";
for (lbl = rdo.nextSibling; lbl && lbl.nodeName.toUpperCase() !== "LABEL"; lbl = lbl.nextSibling) {
}
if (lbl) {
    lbl.style.display = "none";
}

But I have a better option for you: It seems to be a well-kept secret that label elements can contain the input they relate to, and when they do no for is required at all. So if you change your HTML to:

<div id="myformelement">
   <label><input type="radio" id="option1"> Option 1</label>
   <label><input type="radio" id="option2"> Option 2</label> 
   <label><input type="radio" id="option3"> Option 3</label> 
   <label><input type="radio" id="option4"> Option 4</label>  
</div>

...it gets a lot easier:

document.getElementById("option2").parentNode.style.display = "none";

You just find the input, traverse up to its parent which is the label, and hide that (which will hide the input as well).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875