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
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
Share Improve this question edited Jan 5, 2011 at 16:17 TeAmEr asked Jan 5, 2011 at 16:10 TeAmErTeAmEr 4,76913 gold badges66 silver badges108 bronze badges 1- is this straight JS or jQuery? – hunter Commented Jan 5, 2011 at 16:15
3 Answers
Reset to default 3If 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;
}
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>
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.