user6322087 user6322087 - 6 months ago 19
jQuery Question

Get state of select box

Im doing some Ajax filtering from a SQL database, and currently im using checkboxes, which works as they should.
I have some filters that i need to get from a select box instead, and i need your help with getting the state of the select box into my function

The functions looks like this:

function searchOptions() {
var opts = [];
$checkboxes.each(function() {
if (this.checked) {
opts.push(this.name);
}
});
return opts;
};


HTML for checkboxes:

<input type="checkbox" name="type1">
<input type="checkbox" name="type2">


HTML for select box:

<select>
<option value="value1">option1</option>
<option value="value2">option2</option>
<option value="value3">option3</option>
</select>


How do i do the same with a select box? I need to check whether it's set or not, and get the value from the
<option>

For the checkbox i use the name attribute, and i'm not quite sure that's a proper attribute for
<option>
?

Answer

In selects you need not worry about options. The select value can be extracted from select attribute itself You could try something like this:

function searchSelectOptions(){

var opts = [];
$('YOUR-SELECT-CLASS').each(function(){
    if($(this).val()!=='' || typeof $(this).val()!=='undefined'){
       opts.push(this.val());
    }
    });
return opts;

};

EDIT If you've defined your options and their values doesn't have empty string (Which is the case after OP edit). You could just do:

function searchSelectOptions(){

var opts = [];
$('YOUR-SELECT-CLASS').each(function(){
   opts.push(this.val());
});
return opts;

};