我想实现:
如果我在第一个选择框中选择“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();">
您可以在此处查看一个工作示例:
关于javascript - 如果选择选项中的值低于第二个选择选项中的值,则更改选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480653/