2

I want to be able to hide certain options in html "select", which have value greater that a specific variable:

This is a simple "select" in my html with all options initially available:

<select class="form-control" id="results_per_page">
    <option value="4">4</option>
    <option value="8">8</option>
    <option value="12">12</option>
    <option value="16">16</option>
    <option value="20">20</option>
    <option value="28">28</option>
    <option value="40">40</option>
    <option value="80">80</option>
    <option value="120">120</option>
</select>

Now, my script looks like this:

var itemsFound = "22"; //that's an example -can be any number

// I want to hide the options that are greater than "itemsFound"
$('#results_per_page').find('option[value > "'+itemsFound+'"]').hide();

The line above returns "Uncaught Error: Syntax Error, unrecognized expression: option[value > "22"]

When I use the "equal" though, it works:

$('#results_per_page').find('option[value = "40"]').hide(); //the option with value "40" is indeed hidden

Any ideas of how could this implemented?

Theo Orphanos
  • 1,417
  • 1
  • 19
  • 27
  • Agreed with @Andreas - look at the post he linked; it has the answer you're looking for there – Nick Zuber Nov 25 '15 at 17:19
  • 1
    @Andreas: I looked at that post and actually does provide an answer... When I asked the question though, in my mind I was focusing in html "select" element and neglected to check this question which in fact provides a solution but for a much wider spectrum... However, since my question focuses on html "select" element, I believe that it can be helpful to others with similar problem regarding this particular element. Therefore, I am not sure if it should really be marked as "duplicate"... – Theo Orphanos Nov 25 '15 at 17:41

1 Answers1

2

You can iterate through each item and check the values:

var itemsFound = "22"; //that's an example -can be any number
itemsFound = parseInt(itemsFound, 10);
//iterate through each option
$('#results_per_page option').each(function() {
  //better use parseInt to avoid unexpected bahavour
  currentItem = parseInt($(this).attr("value"), 10);
  //your condition
  if (currentItem > itemsFound) {
    $(this).hide();
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="form-control" id="results_per_page">
  <option value="4">4</option>
  <option value="8">8</option>
  <option value="12">12</option>
  <option value="16">16</option>
  <option value="20">20</option>
  <option value="28">28</option>
  <option value="40">40</option>
  <option value="80">80</option>
  <option value="120">120</option>
</select>
Alex Char
  • 32,879
  • 9
  • 49
  • 70