简体   繁体   中英

Get text node from checked radio button

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

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> 

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;

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM