How to create radio buttons dynamically?

生来就可爱ヽ(ⅴ<●) 提交于 2021-01-29 20:38:39

问题


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> 

`


回答1:


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:
  • createElement().
  • insertBefore().
  • parentNode.



回答2:


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



来源:https://stackoverflow.com/questions/9574167/how-to-create-radio-buttons-dynamically

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