简体   繁体   English

如何动态创建单选按钮?

[英]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: 我在动态创建单选按钮时遇到问题,我有一个文本框和一个按钮,我要求用户在文本字段中输入一个值,然后我检索文本框值,并在他按A时使用它来创建单选按钮按钮,我在javaScript中尝试了此代码,但在单击指定按钮时并没有创建单选按钮:

<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> 

` `

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 . JS小提琴演示


References: 参考文献:

Here are the problems as I can see them: 我可以看到的是以下问题:

  • In your #AddButton click function, you pass a variable checked which does not exist. 在您的#AddButton单击函数中,您传递了一个已checked不存在的变量。
  • You don't pass the element returned from createRadioElement to anything that will insert it into the DOM 您不会将createRadioElement返回的元素createRadioElement给将其插入DOM的任何元素

I fixed those by basically changing your #AddButton click function to the following: 我通过将#AddButton click函数基本上更改为以下内容来修复了这些问题:

$("#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. 您可能需要更改此设置,以便将单选按钮附加到#RadioArea元素的末尾,而不是完全替换内容。

See demo 观看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM