首页 > 解决方案 > 如何使用下拉列表对单选按钮进行逻辑分组

问题描述

function radioCheck() {
  document.getElementById("last").checked = "checked";
}
<label> 
<input type="radio" name="Ppub" value="" checked="checked">All Dates 
</label>

<br>

<label>
<input type="radio" id="last" name="Ppub" value=""> Last 
</label>

<select name="Ppub" id="selectRange" value="" onchange="radioCheck();">
  <option value="">Select</option>
  <option value="20181220-20190120">month</option>
  <option value="20180720-20190120">6 months</option>
  <option value="20180120-20190120">year</option>
</select>

我正在处理一个搜索表单,我有一组单选按钮来过滤搜索。对于其中一个单选按钮,我希望它“链接”到下拉菜单。

当用户从菜单中选择一个项目时,我可以使单选按钮的状态为“选中”。但是,如果用户选中另一个单选按钮,则仍使用所选项目的值。

如何对单选按钮和下拉菜单进行分组?我尝试将它们放在同一个标​​签中,但无济于事。

标签: javascripthtml

解决方案


您必须在单击单选按钮时重置下拉菜单。我也找不到下拉名称的任何理由,因为它与单选按钮相同。

请注意单选按钮的属性变化。

var radio = document.querySelector('[value=all]');
radio.onclick = function(){
  document.getElementById("selectRange").selectedIndex = 0;
}

function radioCheck() {
  document.getElementById("last").checked = "checked";
}
<label> 
  <input type="radio" name="Ppub" value="all" checked="checked">All Dates 
</label>

<br>

<label>
  <input type="radio" id="last" name="Ppub" value="last"> Last 
</label>

<select id="selectRange" value="" onchange="radioCheck();">
  <option value="">Select</option>
  <option value="20181220-20190120">month</option>
  <option value="20180720-20190120">6 months</option>
  <option value="20180120-20190120">year</option>
</select>

可能以下内容可以帮助您实现您正在寻找的东西(请注意 HTML 中的变化,每组单选和选择的包装 div)。

var radioAll = document.querySelectorAll('[type=radio]');
radioAll.forEach(function(r){
  r.onclick = function(){
    var ddAll = document.querySelectorAll('select');
    ddAll.forEach(function(s){
      s.selectedIndex = 0;
    }); 
  }
});


function radioCheck(el) {
  var input = el.parentNode.querySelector('[name=Ppub]');
  input.checked = "checked";
}
<label> 
  <input type="radio" name="Ppub" value="all" checked="checked">All Dates 
</label>

<br>
<div>
  <label>
    <input type="radio" id="last" name="Ppub" value="last"> Last 
  </label>

  <select id="selectRange" value="" onchange="radioCheck(this);">
    <option value="">Select</option>
    <option value="20181220-20190120">month</option>
    <option value="20180720-20190120">6 months</option>
    <option value="20180120-20190120">year</option>
  </select>

</div>
<div>
  <label>
    <input type="radio" name="Ppub" value=""> Cutom range 
  </label>

  <select value="" onchange="radioCheck(this);">
    <option value="">Select</option>
    <option value="20181220-20190120">Test1</option>
    <option value="20180720-20190120">Test2</option>
    <option value="20180120-20190120">Test3</option>
  </select>
</div>


推荐阅读