最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Need help in creating radio buttons dynamically - Stack Overflow

programmeradmin0浏览0评论

i have a problem in setting the labels and alignment of dynamically created radio buttons , i want to retrieve a value from a text box and use this value as a label for the new generated radio button, i tried this code it generates radio button but it doesn't give it a label(the one retrieved from the text box) also it generate radio buttons horizontally not vertically:
HTML:

<input type="text" name="option" id="option" value=""  /><br>
<div id="AddButton" data-role="button" data-inline="true">Add</div>

<div data-role="fieldcontain">
  <fieldset data-role="controlgroup">
    <legend>Choose an Option:</legend><br><br>
    <div id="after">

    </div>
  </fieldset>
</div>

JavaScript:

<script>
  function createRadioElement(elem, label, checked) {
    var input = document.createElement('input');
    input.type = 'radio';
    input.label = value;

    if (checked) {
      input.checked = 'checked';
    }
    elem.parentNode.insertBefore(input,elem.nextSibling)
  }    

  $( '#admin' ).live( 'pageinit',function(event){
    $('#AddButton').click(function(){
      var x = document.getElementById('option').value

      createRadioElement(this,$('#option').val());
    }); 
  });
</script>

i have a problem in setting the labels and alignment of dynamically created radio buttons , i want to retrieve a value from a text box and use this value as a label for the new generated radio button, i tried this code it generates radio button but it doesn't give it a label(the one retrieved from the text box) also it generate radio buttons horizontally not vertically:
HTML:

<input type="text" name="option" id="option" value=""  /><br>
<div id="AddButton" data-role="button" data-inline="true">Add</div>

<div data-role="fieldcontain">
  <fieldset data-role="controlgroup">
    <legend>Choose an Option:</legend><br><br>
    <div id="after">

    </div>
  </fieldset>
</div>

JavaScript:

<script>
  function createRadioElement(elem, label, checked) {
    var input = document.createElement('input');
    input.type = 'radio';
    input.label = value;

    if (checked) {
      input.checked = 'checked';
    }
    elem.parentNode.insertBefore(input,elem.nextSibling)
  }    

  $( '#admin' ).live( 'pageinit',function(event){
    $('#AddButton').click(function(){
      var x = document.getElementById('option').value

      createRadioElement(this,$('#option').val());
    }); 
  });
</script>
Share Improve this question edited Mar 6, 2012 at 15:30 Veger 37.9k11 gold badges108 silver badges117 bronze badges asked Mar 6, 2012 at 9:12 Eslam HamdyEslam Hamdy 7,39627 gold badges107 silver badges167 bronze badges 2
  • 1 this [question (How do you dynamically create a radio button in Javascript...)][1] can help you to i think [1]: stackoverflow./questions/118693/… – Pben Commented Mar 6, 2012 at 9:20
  • i already know how to create radio buttons dynamically, but i didn't know how to set their labels and their alignment – Eslam Hamdy Commented Mar 6, 2012 at 9:22
Add a ment  | 

4 Answers 4

Reset to default 2

You could do something like

$('#AddButton').click(function(){
  var label = document.getElementById('option').value;
   $radio = $('<input />', { type: "radio" });
   var $label = $('<label />', { text: label});
   var wrapper = $('<div />');
   wrapper.append($label).append($radio);;

    $('div#after').append(wrapper);

}); 

fiddle here http://jsfiddle/h8g6S/

Since you're using jQuery, you can leverage the .clone() method to copy an existing chunk of markup. What I do is "hide" a template section outside of the form, then copy what I need and change the attributes (such as "name," "id," and so on) as needed.

Here's the API reference: http://api.jquery./clone/

EDIT: Here's an example...

<div id="radiobtn_tmpl">
    <input type="radio" class="rdio btn" />
    <label class="rdio lbl" for=""></label>
</div>

...

stuff here...

...

<script>
    var _template = $('#radiobtn_tmpl').clone();

    _template.removeAttr('id');
    _template.find('.rdio.btn').attr({ 'name' : "teh_button", 'id' : "teh_button" });
    _template.find('.rdio.lbl').attr({ 'for' : "teh_button" }).html('Your label text');

    $(_template).appendTo($('#after'));
</script>

This should get you started:

function createRadioElement(elem, label, checked) {
    var id = 'option1_' + label;
    $('#after').append($('<input />', {
        'type': 'radio',
        'name': 'option1',
        'id': id,
        'value': '1'
    }));
    $('#after').append('<label for="' + id + '">' 
                        + label + '</label><br />');
 }

$('#AddButton').click(function(){
    var x = document.getElementById('option').value;
    createRadioElement(this,$('#option').val());
}); 

See Demo: http://jsfiddle/HaBhk/2/

I see a lot of answers here for how to dynamically add radio buttons using jQuery, but not many that show how to enhance dynamic radio buttons using jQuery Mobile.

The trick is to call .checkboxradio() on the newly created radio buttons.

If you programmatically change the values later on, you would then call .checkboxradio('refresh')

Demo here: http://jsfiddle/kiliman/4wDU7/7/

$(document).bind('pageinit', function(e, data) {
    var $container = $('#optionsgroup').find('.ui-controlgroup-controls');

    // build radio button list
    for (var i = 0; i < 3; i++) {
        var id = 'option_' + i,
            label = 'Option ' + i;

        $('<input />', {
            'id': id,
            'type': 'radio',
            'name': 'options',
            'value': i
        })
        .append('<label for="' + id + '">' + label + '</label>')
        .appendTo($container);
    }
    // enhance radio buttons
    $container.find('input[type=radio]').checkboxradio();
});
发布评论

评论列表(0)

  1. 暂无评论