javascript - 如果选择选项中的值低于第二个选择选项中的值,则更改选项

标签 javascript jquery if-statement

我想实现:

如果我在第一个选择框中选择“16”,并在第二个选择框中选择更大的值,例如“17”,则在第二个选择框中选择自动更改为“16”。

如果第一个选择框中的值低于第二个选择框中的值,请始终更改为相同的值,例如 16 到 16、18 到 18。

<select id="from_age_js" name="from_age" class="select-advertise-style">
   <option value="f13">13</option>
   <option value="f14">14</option>
   <option value="f15">15</option>
   <option value="f16">16</option>
   <option value="f17">17</option>
   <option value="f18" selected>18</option>
   <option value="f19">19</option>
   <option value="f20">20</option>
</select>
—
<select id="to_age_js" name="to_age" class="select-advertise-style">
   <option value="t13">13</option>
   <option value="t14">14</option>
   <option value="t15">15</option>
   <option value="t16">16</option>
   <option value="t17">17</option>
   <option value="t18">18</option>
   <option value="t20" selected>20+</option>
</select>

最佳答案

这很简单,就你的情况而言,使用纯 JavaScript,我会做这样的事情:

function checkit()
{

//Store the two dropdowns for easy reference
var fromAge = document.getElementById('from_age_js');
var toAge = document.getElementById('to_age_js');

//Verify if the toAge value is minor, to see if the conditional code will be executed
if( fromAge.options[fromAge.selectedIndex].value > 
        toAge.options[toAge.selectedIndex].value)
    {
        //In that case, match the values to be the same...
        document.getElementById('to_age_js').value =
      fromAge.options[fromAge.selectedIndex].value;
    }

}

您只需将该函数添加到您想要调用它的位置即可。我会选择在选择下拉列表中添加来自 Javascript 的 onchange 事件。像这样:

<select id="from_age_js" name="from_age" class="select-advertise-style" onchange="checkit();">

您可以在此处查看一个工作示例:

https://jsfiddle.net/8cmad3tz/19/

关于javascript - 如果选择选项中的值低于第二个选择选项中的值,则更改选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480653/

相关文章:

excel - 如何在Excel函数中引用 "#VALUE!"

javascript - Web 应用程序选择选项中的文本框

javascript - JS 数字方法不起作用

javascript - 在 jQuery .html() 更新时,其他功能停止工作

javascript - 无法让 DataTables 与 Jade 一起使用

jquery - 如何让我的 div 显示选定的 youtube api 内容?

javascript - 单击按钮时下载文件 jQuery

PHP 使用条件 if/elseif/else 创建 MySQL 查询

javascript - 动态创建独特的按钮

shell - 运行 `if ! command; then`时如何获取退出代码?