Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text node from checked radio button

Tags:

javascript

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"?

like image 790
Doug Fir Avatar asked Jan 06 '23 16:01

Doug Fir


2 Answers

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;
like image 70
Josh Crozier Avatar answered Jan 19 '23 09:01

Josh Crozier


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>
like image 35
Arun P Johny Avatar answered Jan 19 '23 09:01

Arun P Johny