11

I am trying to convert select boxes to radio buttons on the fly using jQuery, and I'm not sure the best way.

Example HTML:

  <form id="product">    
    <select name="data[123]">
      <option value="1">First</option>
      <option value="2">Second</option>
      ......
      <option value="n">xxxxxx</option>
    </select>
  </form>

I want to convert it at page load using jquery to:

<form id="product">
  <input type="radio" name="data[123]" value="1" />
  <label for="data[123]">First</label><br/>
  <input type="radio" name="data[123]" value="2" />
  <label for="data[123]">Second</label><br/>
  ......
  <input type="radio" name="data[123]" value="n" />
  <label for="data[123]">xxxxxx</label><br/>
</form>

And it needs to be dynamic so it will loop dynamically for each select box and each option inside (as different products have different options)

I'm trying to figure the best way. Either to get a multidimensional array of all the values first and then build the radio buttons.. or swap them out one at a time in a loop. Currently attempting the former, but I think I may be overthinking it:

$(document).ready(function(){
    
    //Get Exising Select Options    
    $('form#product select').each(function(i, select){
        $(select[i]).find('option').each(function(j, option){
            //alert($(option).text());
            option[j] = [];
            option[j]['text'] = $(option).text();
            option[j]['val'] = $(option).val();
        });
    });
    
    
    //Remove Select box
    $('form#product select').remove();
});

Has anyone tried this or have some secret/easier way of doing it that I'm missing?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Dss
  • 113
  • 1
  • 1
  • 4

2 Answers2

29

I put this together, and tested it in a few browsers, all seem to handle it well. It will take the data out of the <option> elements and create the <input/><label/><br/> for each one, then remove the select box.

//Get Exising Select Options    
$('form#product select').each(function(i, select){
    var $select = $(select);
    $select.find('option').each(function(j, option){
        var $option = $(option);
        // Create a radio:
        var $radio = $('<input type="radio" />');
        // Set name and value:
        $radio.attr('name', $select.attr('name')).attr('value', $option.val());
        // Set checked if the option was selected
        if ($option.attr('selected')) $radio.attr('checked', 'checked');
        // Insert radio before select box:
        $select.before($radio);
        // Insert a label:
        $select.before(
          $("<label />").attr('for', $select.attr('name')).text($option.text())
        );
        // Insert a <br />:
        $select.before("<br/>");
    });
    $select.remove();
});
gnarf
  • 105,192
  • 25
  • 127
  • 161
  • thanks but label clicks not working replace two lines 1: **`$radio.attr('name', $select.attr('name')).attr('id', $option.val()); `**2.**`$("").attr('for', $option.attr('value')).text($option.text()) );`** – John Oct 26 '13 at 09:58
  • actually the second line should be replaced like this `$(" – Claudiu Creanga Apr 06 '15 at 13:57
  • This solution worked great for me after a few minor changes: `$option.attr('selected')` needed to be `$option.is(':selected')` because my dropdown did not have any option with the selected attribute (the first one was pre-selected.) I also had to create an ID for the radio button, so that the for="" would work. `$radio.attr('id', $select.attr('id') + '_' + $option.attr('value'));` Once your radio has its own unique ID, @Claudiu's suggestion will work. In my case, they didn't have their own IDs yet. – Eric Seastrand Mar 24 '16 at 22:37
  • I needed to add one string to make the select react on radios change $radio.on('change', function() {$('select.orderby').val($option.val()).trigger('change');}); and to replace $select.remove(); to select(hide); maybe will be useful for someone, in generally your script helped very much, after that 13 years – libertarian Jul 07 '23 at 16:19
1

You're on the right track. Iterate and collect the select data into variables and make as few DOM operation calls as possible (for efficiency) to create the radio inputs.

micahwittman
  • 12,356
  • 2
  • 32
  • 37