[英]how to disable dropdown options less than some value using jquery
Below I have a year dropdown.下面我有一年的下拉菜单。
<select name="from_year" class="col-md-4 form-control" id="from_year">
<option value="0">Select Year</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option selected="selected" value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
Now from ajax call I get some year say 2016. Now I want to disable all options less than 2016. I tried following:现在从 ajax 调用我得到一些年份说 2016。现在我想禁用小于 2016 的所有选项。我尝试了以下操作:
$('select#from_year option:lt('+payment_date[1]+')').prop("disabled", true);
. . . . . . where payment_date[1] = 2016
, but to no avail.其中payment_date[1] = 2016
,但无济于事。
Am I doing something wrong.难道我做错了什么。 Any help/suggestions are welcome.欢迎任何帮助/建议。
You can use filter()
to achieve this:您可以使用filter()
来实现这一点:
var year = 2016; $('#from_year option').filter(function() { return $(this).val() < year; }).prop('disabled', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <select name="from_year" class="col-md-4 form-control" id="from_year"> <option value="0">Select Year</option> <option value="2010">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option selected="selected" value="2015">2015</option> <option value="2016">2016</option> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> </select>
- Update - - 更新 -
Note that the syntax for the filter()
function can now be simplified using ES6 arrow functions:请注意,现在可以使用 ES6 箭头函数简化filter()
函数的语法:
$('#from_year option').filter((i, el) => el.value < year).prop('disabled', true);
Rory's answer is great (I upvoted it :) ), but here is one that is more of an adaptation of what you initially tried: Rory 的回答很棒(我赞成 :)),但这里的回答更像是对您最初尝试的内容的改编:
var $group = $("select#from_year");
var iTarget = $group.find("[value='" + payment_date[1] + "']").index();
$group.find(":lt(" + iTarget + ")").prop("disabled", true);
The key difference is that jQuery's :lt()
runs off of an elements index within its selector group, rather than its value.关键的区别在于 jQuery 的:lt()
运行在其选择器组中的元素索引,而不是它的值。 So you have to retrieve the index of the "2016" <option>
before you can compare the other indexes to it with :lt()
.因此,您必须先检索“2016” <option>
的索引,然后才能将其他索引与:lt()
进行比较。
Note: That would also disable the "Select Year" option which may or may not cause you issues.注意:这也会禁用“选择年份”选项,这可能会或可能不会导致您出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.