3

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>
Veger
  • 37,240
  • 11
  • 105
  • 116
Eslam Hamdy
  • 7,126
  • 27
  • 105
  • 165
  • 1
    this [question (How do you dynamically create a radio button in Javascript...)][1] can help you to i think [1]: http://stackoverflow.com/questions/118693/how-do-you-dynamically-create-a-radio-button-in-javascript-that-works-in-all-bro – Pben Mar 06 '12 at 09: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 Mar 06 '12 at 09:22

4 Answers4

2

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.com/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>
Tieson T.
  • 20,774
  • 6
  • 77
  • 92
  • what's the relation between the .clone method and my problem, i didn't understand! – Eslam Hamdy Mar 06 '12 at 09:20
  • 1
    The relation is: use what's in the library rather than reinventing the wheel. I'll add an example, if you need it. – Tieson T. Mar 06 '12 at 09:22
  • It's probably worth mentioning that the jQuery code goes inside a function or bound eventhandler, not in the global scope like the code above implies. This isn't meant to be 100% functional as-is, just a start. – Tieson T. Mar 07 '12 at 06:00
2

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.net/HaBhk/2/

PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
  • that's great, but how to make them vertically aligned instead of horizontally – Eslam Hamdy Mar 06 '12 at 09:27
  • 1
    `$('#after').append('
    ');`
    – PiTheNumber Mar 06 '12 at 09:37
  • 1
    Made an update. Now it is vertically aligned and only one button is selected. Even nicer with correct labels so you can also click the label text. – PiTheNumber Mar 06 '12 at 09:56
  • can i generate jQuery mobile native radio butttons instead of the Standard HTML radio buttons? – Eslam Hamdy Mar 06 '12 at 11:05
  • You can do that with `.trigger( "create" );` see the [manual](http://jquerymobile.com/test/docs/forms/docs-forms.html) "Initializing groups of dynamically-injected form elements" – PiTheNumber Mar 06 '12 at 11:16
  • .trigger("create"); can provide me with native jQuery mobile radio buttons like the ones here?http://jquerymobile.com/demos/1.1.0rc.1/docs/forms/radiobuttons/ – Eslam Hamdy Mar 06 '12 at 11:36
  • It should. Try adding `
    ` around the radios.
    – PiTheNumber Mar 06 '12 at 11:51
  • i tried to generate a jQuery Mobile native radio button, but it generates a textbox instead, see demo http://jsfiddle.net/HaBhk/4/ – Eslam Hamdy Mar 06 '12 at 12:30
  • what's the change, it generates the same Standard HTML radio button – Eslam Hamdy Mar 06 '12 at 12:51
  • you wrote: `but it generates a textbox instead`. Now it doesn't. Also try to use trigger create like this: http://jsfiddle.net/HaBhk/7/ – PiTheNumber Mar 06 '12 at 13:03
  • 1
    Anyway, try to get an understanding of what you are doing. Change the script you have until you know what every tiny char is for, why it's there and how you could use it in other places. Read some tutorials and look at some demo scripts. – PiTheNumber Mar 06 '12 at 13:06
  • i was trying to generate a native radio button, at this time it was generating a textbox instead, that's what i was doing – Eslam Hamdy Mar 06 '12 at 13:12
  • i guess that i have to create a wrapping element and put the generated radio buttons in it, after that i have to call .page() on the newly generated element – Eslam Hamdy Mar 06 '12 at 13:39
  • i have a problem in removing, when i press the remove button, it removes all the group, i want to remove them separably: Demo here http://jsfiddle.net/HaBhk/10/ – Eslam Hamdy Mar 07 '12 at 12:20
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.net/h8g6S/

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
1

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.net/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();
});
Kiliman
  • 18,460
  • 3
  • 39
  • 38