Eslam Hamdy
Eslam Hamdy

Reputation: 7396

How to create radio buttons dynamically?

i have a problem in creating radio buttons dynamically, i have a text box and a button, i asked the user to input a value in the text field then i retrieve the text box value and use it to create a radio button when he press a button, i tried this code in javaScript but it doesn't create a radio button on clicking the specified button:

<script type="text/javascript" >
    function createRadioElement(value, checked) {
        var radioHtml = '<input type="radio" value="' + value + '"';
        if ( checked ) {
            radioHtml += ' checked="checked"';
        }
        radioHtml += '/>';

        var radioFragment = document.createElement('div');
        radioFragment.innerHTML = radioHtml;

        return radioFragment.firstChild;
    }

    $( '#admin' ).live( 'pageinit',function(event){

        $( "#AddButton" ).bind( "click", function(event, ui) {

            var x=document.getElementById('option').value

            createRadioElement(x, checked);
        });
    });
</script> 

`

Upvotes: 0

Views: 8110

Answers (2)

David Thomas
David Thomas

Reputation: 253486

Try the following for the creation of a radio input:

function createRadioElement(elem, value, checked) {
    var input = document.createElement('input');
        input.type = 'radio';
        input.value = value;
        if (checked) {
            input.checked = 'checked';
        }

    elem.parentNode.insertBefore(input, elem.nextSibling);
}

JS Fiddle demo.


References:

Upvotes: 4

mVChr
mVChr

Reputation: 50205

Here are the problems as I can see them:

  • In your #AddButton click function, you pass a variable checked which does not exist.
  • You don't pass the element returned from createRadioElement to anything that will insert it into the DOM

I fixed those by basically changing your #AddButton click function to the following:

$("#AddButton").bind("click", function(event) {
    var x = document.getElementById('option').value,
        $ra = $('#RadioArea');

    $ra.html(createRadioElement(x, true));
});​

You'll probably want to change this so it appends the radio button to the end of whatever your #RadioArea element is instead of replacing the contents completely.

See demo

Upvotes: 2

Related Questions