4

Here is a piece of html for a radio button that is currently selected:

<label>
    <input type="radio" name="reason" value="1" data-promo="1">
    "some text here bla bla"
</label>

With a line of JS I found over here I am able to grab the input element but not the text:

document.querySelector('input[name="reason"]:checked');

Returns:

<input type="radio" name="reason" value="1" data-promo="1">

How would I grab the text that follows this element "some text here bla bla"?

Community
  • 1
  • 1
Doug Fir
  • 19,971
  • 47
  • 169
  • 299

4 Answers4

4

The text node is the next sibling of the checkbox so

function test() {
  var checkbox = document.querySelector('input[name="reason"]:checked');
  if (checkbox) {
    var text = checkbox.nextSibling.textContent;
    alert(text);
  }
}
<label>
  <input type="radio" name="reason" value="1" data-promo="1">text 1
</label>
<label>
  <input type="radio" name="reason" value="2" data-promo="2">text 2
</label>
<label>
  <input type="radio" name="reason" value="3" data-promo="3">text 3
</label>
<label>
  <input type="radio" name="reason" value="4" data-promo="4">text 4
</label>
<button onclick="test()">Test</button>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
4

If you don't know the position of the text in advance, then the simpliest option is to access the textContent property of the parent label element:

document.querySelector('input[name="reason"]:checked').parentElement.textContent;

Of course, this assumes that is the only text node in the label element.


Alternatively, if the text always appears after the input element, then you could just access the textContent property of the next sibling:

document.querySelector('input[name="reason"]:checked').nextSibling.textContent;
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1

If you want to using javascript as you do then try this-

alert(document.querySelector('input[name="reason"]:checked').nextSibling.textContent);

You may do something like this using jQuery as well,

$('input[name="reason"]').on("click", function(){
    alert($(this).closest("label").text());
});
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
0

I did a small change to the your code. Added data-txt and used getAttribute

var a = document.querySelector('input[name="reason"]:checked').getAttribute("data-txt");
alert(a);

Check how this works for you.

Sameera Thilakasiri
  • 9,452
  • 10
  • 51
  • 86