将动态标签赋予单选按钮

Leo*_*dus 0 html javascript

我正在尝试创建动态表单,因此单击按钮后,我将其称为Javascript函数。这是函数:

function addradiobutton(type){
    var element = document.createElement("input");
    //Assign different attributes to the element.
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);   

    var foo = document.getElementById("fooBar");
    //Append the element in page (in span).
    foo.appendChild(element);
    counter=counter+1;
 }
Run Code Online (Sandbox Code Playgroud)

此代码添加了一个单选按钮,其标签如下所示

<input type="radio" name="radio" value="radio">
Run Code Online (Sandbox Code Playgroud)

但我想使这段代码像这样。

 <input type="radio" name="radio" value="radio">WATER</input>
Run Code Online (Sandbox Code Playgroud)

我不介意关闭输入标签,但我想在代码末尾获取值“ Water”。
仅以水为例,其价值也是动态的。
我该怎么办 ?

yog*_*ogi 6

尝试这个

<script type="text/javascript">
        var counter = 0;
        function addradiobutton(type, text) {
            var label = document.createElement("label");

            var element = document.createElement("input");
            //Assign different attributes to the element.
            element.setAttribute("type", type);
            element.setAttribute("value", type);
            element.setAttribute("name", type);

            label.appendChild(element);
            label.innerHTML += text;

            var foo = document.getElementById("fooBar");
            //Append the element in page (in span).
            foo.appendChild(label);
            counter = counter + 1;
        }
        addradiobutton("radio", "Water");
</script>
Run Code Online (Sandbox Code Playgroud)