[英]Get text node from checked radio button
Here is a piece of html for a radio button that is currently selected: 这是一个当前选中的单选按钮的html:
<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: 有了我在这里找到的一行JS,我能够获取输入元素而不是文本:
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"? 我如何抓住这个元素后面的文字“这里有些文字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: 如果您事先不知道文本的位置,那么最简单的选项是访问父label
元素的textContent
属性 :
document.querySelector('input[name="reason"]:checked').parentElement.textContent;
Of course, this assumes that is the only text node in the label
element. 当然,这假设它是label
元素中唯一的文本节点。
Alternatively, if the text always appears after the input
element, then you could just access the textContent
property of the next sibling : 或者,如果文本总是出现在 input
元素之后,那么您可以只访问下一个兄弟的textContent
属性:
document.querySelector('input[name="reason"]:checked').nextSibling.textContent;
If you want to using javascript as you do then try this- 如果你想像你一样使用javascript,那么试试这个 -
alert(document.querySelector('input[name="reason"]:checked').nextSibling.textContent);
You may do something like this using jQuery as well, 您也可以使用jQuery做这样的事情,
$('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
添加了data-txt
并使用了getAttribute
var a = document.querySelector('input[name="reason"]:checked').getAttribute("data-txt");
alert(a);
Check how this works for you. 检查这对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.