hybrid
hybrid

Reputation: 3968

jQuery selector for select elements with empty value attributes?

I'm using the below selector to get all the form inputs that are pre-populated with a value.

$('input[value!=""]');

This works great and so I thought I could apply the same logic to my select elements using the following selector, though it seems to be selecting all the select elements in Chrome.

$('select[value!=""]');

Below is an example of two types of selects on the form:

<select name="phone2_type" id="phone2_type">
  <option value="">Select one:</option>
  <option value="HOME">Home</option>
  <option value="CELL">Cell</option>
  <option value="BUSN">Business</option>
</select>

<select name="state" id="state">
  <option value="">Select one:</option>
  <option value="XX">Outside USA/Canada</option>
  <option value="AL" selected="selected">Alabama</option>
  <option value="AK">Alaska</option>
  ...
</select>

I'd like to select the second select since it has a value selected already with the select="selected"

Upvotes: 4

Views: 7114

Answers (3)

j08691
j08691

Reputation: 207891

$('select').has('option[selected="selected"]')

will get the select element. jsFiddle example.

Upvotes: 1

Paolo Casciello
Paolo Casciello

Reputation: 8202

For select you need to use a special selector made available by JQuery: :selected

So

$('#state option:selected').val()

is the current selected value.

If you need the do something on the select elements themself you could do something like:

$('#select option:selected').parents('select').dosomething(...)

Upvotes: 2

thecodeparadox
thecodeparadox

Reputation: 87073

value is not an attribute of select tag.

So you need to try:

var emptySelect = $('select').filter(function() {
                     return $.trim( $(this).val() ) == '';
                  });

Upvotes: 7

Related Questions