JQuery selector for elements with empty value attributes?

I am using the selector below to get all form inputs that are pre-filled with a value.

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

      

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

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

      

Below is an example of two types of selection in a 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 would like to select the second selection as it has the value already selected with select = "selected"

+3


source to share


3 answers


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

      



will get a select element. JsFiddle example .

0


source


value

is not a tag attribute select

.

So, you need to try:



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

      

+6


source


For selection you need to use the special selector available by JQuery :: selected

So

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

      

is the currently selected value.

If you need to do something on the select items themselves, you can do something like:

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

      

+1


source







All Articles