2


i have this code :

<input type=radio name="vote_x" value="5">
    <label for="vote_x">blabla</label><br>

how can i get the label value for radio with id of vote_x [using JS] ??

thanks

Rami Dabain
  • 4,709
  • 12
  • 62
  • 106

3 Answers3

3

If you put an id on the label like this

<input type="radio" name="vote_x" value="5">
<label id="for_vote_x" for="vote_x">blabla</label>

You can then use

var textinlabel = document.getElementById("for_vote_x").innerHTML;

Edited: With out using an id for the label element

var labelElements = document.getElementsByTagName("label");
for (var i = 0, var labelElement; labelElements[i]; i++) {
  if (labelElement.getAttribute("for") == "vote_x") {
    //this is the labelElement you want
    //code goes here
  }
}

Ideally you would want to create a Generic function for this

function getlabelforinput(inputname) {
    var labelElements = document.getElementsByTagName("label");
    for (var i = 0, var labelElement; labelElements[i]; i++) {
      if (labelElement.getAttribute("for") == inputname) {
        return labelElement
      }
    }
    return null;
}
John Hartsock
  • 85,422
  • 23
  • 131
  • 146
1

Modern answer

Use document.querySelector('label[for="INPUT_ID"]') to get the label element corresponding to the input with given id.

Example:

const label = document.querySelector('label[for="vote_x"]');
console.log(label.textContent.trim());
<input type=radio name="vote_x" value="5">

<label for="vote_x">blabla</label>
Andrey Mikhaylov - lolmaus
  • 23,107
  • 6
  • 84
  • 133
0

You can try this

var el = document.getElementById("vote_x");
while(el.nextSibling && !(/label/i.test(el.nextSibling.tagName))){
    el = el.nextSibling;
}
var text = el.nextSibling.innerHTML

You can check it in this fiddle.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I guess this would work but maybe the label isn't guaranteed to be the next sibling? – hunter Jan 05 '11 at 16:23
  • The loop will take care of the text nodes that may come in between the input element and the label. If the position is not fixed then @John's solution (http://stackoverflow.com/questions/4606300/js-get-radio-label-text/4606417#4606355) will be the best one. – Arun P Johny Jan 05 '11 at 16:25