Skip to content Skip to sidebar Skip to footer

Giving Dynamic Label To A Radio Button

I am trying to create a dynamic form so on click of a button I call a Javascript function. here is the function: function addradiobutton(type){ var element = document.createEle

Solution 1:

Try this

<script type="text/javascript">
        var counter = 0;
        functionaddradiobutton(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>

Solution 2:

<inputtype="radio" name="radio" value="radio">WATER</input>

… is invalid HTML. The way to express what you are trying to express is:

<label><inputtype="radio"name="radio"value="radio">WATER</label>

You just need to create a label element, and then appendChild both the input element and the text node.

var label, input;
label = document.createElement('label');
input = document.createElement('input');
// Settype, name, value, etc on input
label.appendChild(input);
label.appendChild('Water');
foo.appendChild(label);

Solution 3:

One solution that I would use is create it not like that but more: (using jQuery for simplicity with syntax)

<divid="buttons"></div><scrpit>
    var temp;
    temp = '<label><inputtype="radio"name="radio"value="radio" />WATER</label>';
    temp + '<label><inputtype="radio"name="radio"value="radio" />WATER1</label>';
    $('#buttons').html(temp);
</script>

Untested but the logic should work, i will try update for errors.

if you want x amount you could put it in a function with a for loop looping to x and iterating those out. Example:

<script>functionaddButtons(number){
        for(var i=0;i<number;i++){
            // do the string appending here
        }
    }
</script>

Solution 4:

This should work.

element.setAttribute("innerHTML","WATER");

Post a Comment for "Giving Dynamic Label To A Radio Button"