javascript 无需修改 HTML 即可将下拉列表转换为单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3974217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:52:02  来源:igfitidea点击:

Convert dropdowns to radio buttons w/o modifying HTML

javascriptjqueryhtmlcss

提问by Thomas

So this is sort of an exceptional case situation - I have a plugin that I can't modify for contractual reasons. It displays a set of drop downs and I need it to display a set of radio buttons instead. Is there a js/jquery method for converting dropdowns to radio buttons w/o changing the HTML. Remember, I can add stuff - I just can modify the plugin (and thus the HTML) directly.

所以这是一种特殊情况 - 我有一个插件,由于合同原因我无法修改。它显示一组下拉菜单,而我需要它来显示一组单选按钮。是否有一种 js/jquery 方法可以在不更改 HTML 的情况下将下拉列表转换为单选按钮。请记住,我可以添加内容 - 我可以直接修改插件(以及 HTML)。

I get that this is a bad way to do it, trust me I don't like it any more than you do.

我知道这是一种糟糕的方式,相信我,我并不比你更喜欢它。

Possibly by detecting the values of the drop-down options and then reformatting them as radio buttons, hiding the original dropdown?

可能通过检测下拉选项的值,然后将它们重新格式化为单选按钮,隐藏原始下拉列表?

<form action="http://example.net/store/cart/" method="post" class="shopp product"> 
  <ul class="variations"> 
    <li> 
      <label for="options-1">Music Download</label> 
      <select name="products[117][options][]" class="category-catalog product117 options" id="options-1">
        <option value="">Select an option</option> 
        <option value="1">Full Album</option> 
        <option value="7">Theme</option> 
        <option value="8">Simian Segue  </option> 
        <option value="9">DK Island Swing</option> 
        <option value="10">Cranky's Theme</option> 
        <option value="11">Cave Dweller Concert</option> 
        <option value="12">Bonus Room Blitz</option> 
        <option value="13">Aquatic Ambiance</option> 
        <option value="14">Candy's Love Song</option> 
        <option value="15">Bad Boss Boogie</option> 
        <option value="16">Mine Cart Madness</option> 
        <option value="17">Life in the Mines</option> 
        <option value="18">Voices of the Temple </option> 
      </select>
    </li>       
  </ul> 

  <p> 
    <select name="products[117][quantity]" id="quantity-117">
      <option selected="selected" value="1">1</option><option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option><option value="5">5</option>
      <option value="6">6</option><option value="7">7</option>
      <option value="8">8</option><option value="9">9</option>
      <option value="10">10</option><option value="11">11</option><option value="12">12</option>
      <option value="13">13</option><option value="14">14</option>
      <option value="15">15</option><option value="20">20</option>
      <option value="25">25</option>
      <option value="30">30</option><option value="40">40</option>
      <option value="50">50</option><option value="75">75</option>
      <option value="100">100</option>
    </select>

    <input type="hidden" name="products[117][product]" value="117" />
    <input type="hidden" name="products[117][category]" value="catalog" />
    <input type="hidden" name="cart" value="add" />
    <input type="submit" name="addtocart"  value="Add to Cart" class="addtocart" />
  </p> 

</form>

回答by BrunoLM

Hide the dropdown and place the new radio elements outside the form, they don't need to post, just update the dropdown value.

隐藏下拉菜单并将新的单选元素放置在表单之外,它们不需要发布,只需更新下拉值即可。

Here is a code example on jsFiddle.

这是 jsFiddle 上的代码示例。

$("#d option").each(function(i, e) { // get the options
    $("<input type='radio' name='r' />") // create a radio element
        .attr("value", $(this).val()) // set the value
        .attr("checked", i == 0) // check the first by default
        .click(function () { // add event click which updates the dropdown
            $("#d").val($(this).val()); // update the dropdown if clicked
        })
        .appendTo("#r"); // append to some visible place
});

回答by Beej

To encapsulate this into a declarative attribute, I extended @BrunoLM 's function to style all <select>'s with a given CSS class into the radio button look.

为了将其封装到声明性属性中,我扩展了 @BrunoLM 的功能,以将具有给定 CSS 类的所有 <select> 样式设置为单选按钮外观。

jsFiddle

js小提琴

HTML

HTML

<select class="radioSelect" id="sizeOptions">
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
    <option value="2XL">2XL</option>
    <option value="3XL">3XL</option>
    <option value="4XL">4XL</option>
    <option value="5XL">5XL</option>
</select>

Result

结果

enter image description here

在此处输入图片说明

CSS

CSS

/* http://jsfiddle.net/496c9/ */
.radioSelectContainer > select {
  display: none;
}

.radioSelectContainer > label {
  display: inline-block;
  margin: 0.3em 0.3em 0 0;
  background-color: #EFEFEF;
  border-radius: 4px;
  border: 1px solid #D0D0D0;
}

  .radioSelectContainer > label > span {
    padding: 0.2em;
    text-align: center;
    display: block;
    white-space: nowrap;
  }

  .radioSelectContainer > label > input {
    position: absolute;
    top: -20px;
  }

    .radioSelectContainer > label > input:checked + span {
      background-color: #404040;
      color: #F7F7F7;
    }

JS

JS

// http://stackoverflow.com/questions/3975331/update-drop-down-selection-with-radio-button-selection-using-jquery
// http://jsfiddle.net/ChinmayeeG/TkGP8/
$(function () {

  $('.radioSelect').each(function (selectIndex, selectElement) {

    var select = $(selectElement);
    var container = $("<div class='radioSelectContainer' />");
    select.after(container);
    container.append(select);

    select.find('option').each(function (optionIndex, optionElement) {
      var radioGroup = select.attr('id') + "Group";
      var label = $("<label />");
      container.append(label);

      $("<input type='radio' name='" + radioGroup + "' />")
          .attr("value", $(this).val())
          //.click((function () { select.val($(this).val()); })) //radio updates select - see optional below
          .appendTo(label);

      $("<span>" + $(this).val() + "</span>").appendTo(label);
    });

    //http://stackoverflow.com/questions/4957207/how-to-check-uncheck-radio-button-on-click
    //optional - this logic handles unchecking when clicking on an already checked radio
    container.find(":radio + span").mousedown(
      function (e) {
        var $span = $(this);
        var $radio = $span.prev();
        if ($radio.is(':checked')) {
          var uncheck = function() {
            setTimeout(function () { $radio.prop('checked', false); }, 0);
          };
          var unbind = function() {
            $span.unbind('mouseup', up);
          };
          var up = function() {
            uncheck();
            unbind();
          };
          $span.bind('mouseup', up);
          $span.one('mouseout', unbind);
        } else {
          select.val($radio.val());
        }
      }
    );

    select.change((function () { //select updates radio
      $("input[name='" + select.attr('id') + "Group" + "'][value='" + this.value + "']").prop("checked", true);
    }));
  });
});