Modify the text of my radio input button?

你。 提交于 2019-12-11 11:41:08

问题


Your average radio button has a name and value, but also some text next to it, in this case "Change this text."

How can I change this in javascript? Or even alert it? AFAIK, it is NOT the .inner html.

HTML:

            <input type="radio" name="radioOption1" value="Array 1"> Change this text

Javascript

    var confirmIExist = document.getElementsByName("radioOption1");
alert(confirmIExist.innerHTML);
    //alerts undefined

If it's not .innerHTML, what is it? if I grab the input object with either getElementByName or getElementById, what chunk after that represents the Alert text?


回答1:


You could use alert(confirmIExist[0].nextSibling.textContent), but wouldn't it be better to place the text next to the radio button in a <label> and then get the inner html of that

<input type="radio" id="radioOption1" name="radioOption1" value="Array 1"><label for="radioOption1" id="r1option">Change this text</label>
...
var label = document.getElementById("r1option");
alert(label.innerHTML);



回答2:


You cannot set inner html for a input element. instead wrap your text with a and give it a ID

<input type="radio" name="radioOption1" value="Array 1"> <label id="radioText">Change this text</label>



回答3:


input is a self-closing element. It cannot have innerHTML

nextSibling will return the Node that follows the radio button.

document.getElementsByName('radioOption1')[0].nextSibling.nodeValue = 'Text changed';

jsFiddle Demo




回答4:


confirmIExist[0].nextSibling.textContent="abc"



来源:https://stackoverflow.com/questions/18179769/modify-the-text-of-my-radio-input-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!