TeAmEr
TeAmEr

Reputation: 4773

js get radio label text


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

Upvotes: 2

Views: 8332

Answers (3)

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>

Upvotes: 1

John Hartsock
John Hartsock

Reputation: 86892

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;
}

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388406

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.

Upvotes: 0

Related Questions