1

I want to ignore/remove all options from a select box that either have a blank value or don't have the value="" attribute at all, e.g.

<option>Any Option</option>
<option value="">Any Option</option>

Here is my jQuery:

$(function() {

  // Create the dropdown base
  $("<select />").appendTo("#pagination_container");

  // Create default option "Go to..."
  $("<option />", {
    "selected": "selected",
    "value"   : "",
    "text"    : "Select Page..."
  }).appendTo("#pagination_container select");

  // Populate dropdown with menu items
  $("#pagination_container a").each(function() {
    var el = $(this);
    $("<option />", {
      "value"   : el.attr("href"),
      "text"    : el.text()
    }).appendTo("#pagination_container select");
  });

  $("#pagination_container select").change(function() {
    window.location = $(this).find("option:selected").val();
  });

});
VNO
  • 3,645
  • 1
  • 16
  • 25
Brajman
  • 307
  • 1
  • 6
  • 16

4 Answers4

1

Target the elements like this

$('option[value=""]');

and to remove do this

$('option[value=""]').remove();
kiranvj
  • 32,342
  • 7
  • 71
  • 76
1

You would need to use a two-part selector to achieve that:

$('option[value=""],option:not([value])').remove();

NOTE: Bear in mind that value="" checks the initial state of the elements. Therefore if you later change the value of the element, and not necessarily the value attribute, then you may get unexpected results. If the values of the option elements are bound to change, please use filter() instead of [value=""].

PeterKA
  • 24,158
  • 5
  • 26
  • 48
0
$("#pagination_container").find("option").each(function(index, el){
  var $el = $(el);
  var value = $el.attr("value");
  if (value === "" || value === undefined)
    $el.remove();
});

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. source

Kevin Wheeler
  • 1,331
  • 2
  • 15
  • 24
0

This question is similar to this questions:

Check the links and learn a lot of diferents way to solve your problem.

Community
  • 1
  • 1
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130