samjhana joshi
samjhana joshi

Reputation: 2015

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:

$('select#from_year option:lt('+payment_date[1]+')').prop("disabled", true);

. . . where payment_date[1] = 2016, but to no avail.

Am I doing something wrong. Any help/suggestions are welcome.

Upvotes: 3

Views: 3390

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337656

You can use filter() to achieve this:

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:

$('#from_year option').filter((i, el) => el.value < year).prop('disabled', true);

Upvotes: 10

talemyn
talemyn

Reputation: 7960

Rory's answer is great (I upvoted it :) ), but here is one that is more of an adaptation of what you initially tried:

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. So you have to retrieve the index of the "2016" <option> before you can compare the other indexes to it with :lt().

Note: That would also disable the "Select Year" option which may or may not cause you issues.

Upvotes: 1

Related Questions