Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

jQuery Remove All Elements from Select with Value

I have simple select that looks like this:

<select id="region">
  <option value=""> -- country -- </option> 
  <option value="842554592">Alberta</option> 
  <option value="708812360">Ontario</option>
  ...
</select>

I want to clear non-blank values and am wondering if jQuery has a simple method for this. I'm using:

$('.country').find('option[value!=""]').remove();

Which seems a bit ugly. Thanks!

Upvotes: 1

Views: 2916

Answers (1)

alex
alex

Reputation: 490263

I want to clear non-blank values and am wondering if jQuery has a simple method for this.

I don't think it is a common enough requirement to expect jQuery to have something like that out of the box.

You could write your own selector if you wanted...

$.expr[':'].nonEmptyValue = function(obj){
   return $(obj).val() != '';
};

$('#region option:nonEmptyValue').remove();

jsFiddle.

If you don't want the custom selector, you could also pass that function to filter() (replace obj with this).

Also, if you wanted to count whitespace only values as empty, do a $.trim() first on the value returned.

Upvotes: 1

Related Questions