td2003
td2003

Reputation: 53

JQuery: removing option from select by data-attribute LESS than

I need to ask you for a help.
I have following select:

<select id="some_id">
    <option value="1" data-cost_level="1">option A</option>
    <option value="4" data-cost_level="2">option B</option>
    <option value="9" data-cost_level="3">option C</option>
</select>

And now I need to remove (using JQuery) all the options with data-cost_level LESS THAN 3.
Is it possible with one-line-instruction without looping through entire select?

Upvotes: 0

Views: 1314

Answers (2)

rmontanodev
rmontanodev

Reputation: 139

Try to get all nodes matching option[data-cost_level] and if attribute "value" is less than 3, remove them with $('selector').remove()

document.querySelectorAll('option[data-cost_level]').forEach((item)=>{
  if($(item).attr('value')<3){
     $(item).remove();
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="some_id">
            <option value="1" data-cost_level="1">option A</option>
            <option value="4" data-cost_level="2">option B</option>
            <option value="9" data-cost_level="3">option C</option>
</select>

Upvotes: 1

fdomn-m
fdomn-m

Reputation: 28611

Your attempt:

// split to 3 lines from 1 so it's easier to see here
$("#some_id").filter(function(){ 
    return $(this).attr('data-cost_level') < "3" }
).remove();

is close.

First, you need to .filter the options not the select, so change to

$("#some_id > option")

next, if you compare strings, you won't get numeric comparison, so ("21"<"3")===true so you need to convert to int, there's various ways to do this, the easiest is to use .data() instead of .attr() which, in jquery, will auto-convert to the correct data type (then compare with an int), ie:

$(this).data("cost_level") < 3

including a test-harness, this gives:

$("#btn").click(() => {
  var val = $("#inp").val() * 1;

  $("#some_id > option").filter(function() {
    return $(this).data("cost_level") < val;
  }).remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="some_id">
  <option value="1" data-cost_level="1">option A</option>
  <option value="4" data-cost_level="2">option B</option>
  <option value="9" data-cost_level="3">option C</option>
</select>
<hr/>
<input id='inp' value='3'><button type='button' id='btn'>clear</button>

Upvotes: 1

Related Questions