jQuery转换选择单选按钮?

Dss*_*Dss 8 jquery select dropbox radio-button

我正在尝试使用jquery将选择框转换为单选按钮,我不确定最好的方法.

示例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>
Run Code Online (Sandbox Code Playgroud)

我想在页面加载时使用jquery将其转换为:

<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>
Run Code Online (Sandbox Code Playgroud)

它需要是动态的,因此它将动态循环每个选择框和内部的每个选项(因为不同的产品有不同的选项)

我想找出最好的方法.要么首先得到所有值的多维数组,然后构建单选按钮..或者在循环中一次交换一个.目前正在尝试前者,但我想我可能会过度思考它:

$(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();
});
Run Code Online (Sandbox Code Playgroud)

有没有人试过这个或者有一些秘密/更简单的方法来做我错过的?

gna*_*arf 25

我把它放在一起,并在几个浏览器中进行测试,似乎都处理得很好.它将从<option>元素中取出数据并<input/><label/><br/>为每个元素创建,然后删除选择框.

//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();
});
Run Code Online (Sandbox Code Playgroud)

  • 太棒了!感谢你们俩! (2认同)