Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - hide options based on value attribute

I need to hide all options when the value attribute is > 23

<select id="category_ids" class="cat-search-pb" multiple >
    <option value="20">Condo for Sale</option>
    <option value="24">&nbsp;&nbsp;- Jomtien</option>
    <option value="25">&nbsp;&nbsp;- Bang Saray</option>
    <option value="21">Condo for Rent</option>
    <option value="22">House for Sale</option>
    <option value="23">House for Rent</option>
    <option value="14">Land</option>
    <option value="15">Commercial</option>
    <option value="18">New Condo Projects</option>
    <option value="19">New House Projects</option> 
</select>

But this code does not work:

$(document).ready(function () {
   $(".cat-search-pb option[value>23]").closest('option').hide();
});

Thanks for your ideas!

like image 480
Petr Beneš Avatar asked Dec 29 '16 16:12

Petr Beneš


2 Answers

You can use jquery filter() on the options that have the value attribute - see demo below:

$(document).ready(function() {
  $(".cat-search-pb option[value]").filter(function() {
    return +$(this).val() > 23;
  }).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="category_ids" class="cat-search-pb" multiple>

  <option value="20">Condo for Sale</option>
  <option value="24">&nbsp;&nbsp;- Jomtien</option>
  <option value="25">&nbsp;&nbsp;- Bang Saray</option>
  <option value="21">Condo for Rent</option>
  <option value="22">House for Sale</option>
  <option value="23">House for Rent</option>
  <option value="14">Land</option>
  <option value="15">Commercial</option>
  <option value="18">New Condo Projects</option>
  <option value="19">New House Projects</option>
</select>
like image 85
kukkuz Avatar answered Oct 31 '22 20:10

kukkuz


Try this, using .filter(). You must convert the value attribute to number using Number() or +$(this)

$(function() 
{
    $(".cat-search-pb option").filter(function() 
    {
        return +$(this).val() > 23;
    }).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="category_ids" class="cat-search-pb" multiple>
    <option value="20">Condo for Sale</option>
    <option value="24">&nbsp;&nbsp;- Jomtien</option>
    <option value="25">&nbsp;&nbsp;- Bang Saray</option>
    <option value="21">Condo for Rent</option>
    <option value="22">House for Sale</option>
    <option value="23">House for Rent</option>
    <option value="14">Land</option>
    <option value="15">Commercial</option>
    <option value="18">New Condo Projects</option>
    <option value="19">New House Projects</option>
</select>
like image 43
Daniel Corzo Avatar answered Oct 31 '22 22:10

Daniel Corzo