[英]Getting text of checked radio button
how to get text instead of value, when I click on the radio button?当我单击单选按钮时,如何获取文本而不是值?
Below code gets Value of the radio button.下面的代码获取单选按钮的值。 I want to take texts (Shows or Movies).
我想接收文本(节目或电影)。 Thanks in advance.
提前致谢。
function myFunction(contentType) { document.getElementById("myspan").innerHTML = contentType; }
<label><input type="radio" oninput="myFunction(this.value)" value="1" name="contentType"><span>Shows</span></label> <label><input type="radio" oninput="myFunction(this.value)" value="2" name="contentType" ><span>Movies</span></label> <span id="myspan" class="text-muted" ></span>
Inside your myFunction() do this:在你的myFunction()里面这样做:
function myFunction(inputRadio) {
document.getElementById("myspan").innerHTML = inputRadio.nextSibling.innerText;
}
In your HTML change this.value to this , and you are good to go!在您的 HTML 中将this.value更改为this ,您就可以开始了!
<label><input type="radio" oninput="myFunction(this)" value="1" name="contentType"><span>Shows</span></label>
<label><input type="radio" oninput="myFunction(this)" value="2" name="contentType" ><span>Movies</span></label>
<span id="myspan" class="text-muted" ></span>
You'll have to either add a data attribute to your radio button, or manually query the DOM to get the text content of the label related to that radio button.您必须向单选按钮添加数据属性,或者手动查询 DOM 以获取与该单选按钮相关的 label 的文本内容。
function myFunction(input) { document.getElementById("myspan").innerHTML = input.dataset.textValue; }
<label><input type="radio" oninput="myFunction(this)" value="1" data-text-value="Shows" name="contentType"><span>Shows</span></label> <label><input type="radio" oninput="myFunction(this)" value="2" data-text-value="Movies" name="contentType" ><span>Movies</span></label> <span id="myspan" class="text-muted" ></span>
function myFunction(contentType) { document.getElementById("myspan").innerHTML = contentType; }
<label><input type="radio" oninput="myFunction(this.value)" value="shows" name="contentType"><span>Shows</span></label> <label><input type="radio" oninput="myFunction(this.value)" value="movies" name="contentType" ><span>Movies</span></label> <span id="myspan" class="text-muted" ></span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.