jquery get select option siblings
I'm trying to get all options other than the selected one and with the different class than the selected one.
Consider the following example:
<select name="country" id="country">
<option value="1" class="option_va开发者_JAVA百科t" selected="selected">United Kingdom</option>
<option value="2" class="option_no_vat">United States</option>
<option value="3" class="option_vat">Spain</option>
<option value="4" class="option_vat">Portugal</option>
</select>
Now when change() event is called I want to get the class of the selected option and classes of other options, which are different to the selected one. In this case the only class that would be added to array would be 'option_no_vat' as Spain and Portugal option have the same class at the selected one (United Kingdom).
Could someone suggest a solution please?
http://jsfiddle.net/vKXMP/1/
$("select#country").change(function(){
var $that, cls;
$that = $(this);
cls = $that.find("option:selected").attr("class"); //returns the class of the selected elements... only works when there is only one class
console.log( $that.find("option").not("."+cls) ) //gives you back a jquery object of all the elements with a different class then the one selected
});
next time, at least try something.
Try this:
var classes;
$('#country').change(function()
{
classes = [];
$(this).find('option:not(:selected)')
.not('.' + $(this).find(':selected').attr('class'))
.each(function()
{
var class = $(this).attr('class');
if ( $.inArray( class, classes ) == -1 )
classes.push(class);
});
});
http://jsfiddle.net/9JEyY/
Note: This'll only work correctly if you have just one class per element.
Here you go
Working demo
$(function(){
$("#country").change(function(){
var classes = [], class;
var currentClass = $(this).find("option:selected").attr('class');
$(this).find("option").each(function(){
class = $(this).attr('class');
if(class != currentClass){
if($.inArray(class, classes) == -1){
classes.push(class);
}
}
});
alert(classes.join(","));
}).change();
});
classes
array will contain all the unique classes which you need.
精彩评论